Javascript 为什么节点JS中对xmlhttprequest post命令的响应是未定义的
我正在尝试使用xmlhttprequest向URL发送请求,并使用NodeJS运行js文件。但对此的反应是不明确的。当我使用CURL命令发布相同的数据时,我得到了正确的响应。为什么它在nodejs和xmlhttprequest的情况下不起作用 这是我写的代码。文件名为test.jsJavascript 为什么节点JS中对xmlhttprequest post命令的响应是未定义的,javascript,node.js,xmlhttprequest,alexa,alexa-voice-service,Javascript,Node.js,Xmlhttprequest,Alexa,Alexa Voice Service,我正在尝试使用xmlhttprequest向URL发送请求,并使用NodeJS运行js文件。但对此的反应是不明确的。当我使用CURL命令发布相同的数据时,我得到了正确的响应。为什么它在nodejs和xmlhttprequest的情况下不起作用 这是我写的代码。文件名为test.js 'use strict'; var readlineSync = require('readline-sync'); var XMLHttpRequest = require("xmlhttprequest
'use strict';
var readlineSync = require('readline-sync');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var urlopen =require("openurl");
var clientId = "amzn1.application-oa2-client.775a44579eaf461b92db3d1a4cb23a5a";
var deviceId = "Test_device1";
var deviceSerialNumber = 123;
var redirectUri = "https://localhost:9745/authresponse";
var responseType ="code";
var clientSecret = "29a6520d97d11d640e030786e133ccec9ead67005aaa45c212e72e10b00900ff";
promptUserLogin();
sleep(10000);
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
var Urlcode = readlineSync.question('enter the code ');
var proceed = readlineSync.question('proceed with execution?');
if(proceed){
getTokenFromCode(Urlcode);
}
function promptUserLogin() {
const scope = 'alexa:all';
const scopeData = {
[scope]: {
productID: deviceId,
productInstanceAttributes: {
deviceSerialNumber: deviceSerialNumber
}
}
};
const authUrl = 'https://www.amazon.com/ap/oa?client_id=' + clientId + '&scope=' + encodeURIComponent(scope) + '&scope_data=' + encodeURIComponent(JSON.stringify(scopeData)) + '&response_type=' + responseType + '&redirect_uri=' + encodeURI(redirectUri);
console.log("abhi avs.js promptUserLogin newWindow");
urlopen.open(authUrl);
}
function getTokenFromCode(CODE) {
return new Promise((resolve, reject) => {
if (typeof CODE !== 'string') {
const error = new TypeError('`code` must be a string.');
this._log(error);
return reject(error);
}
const grantType = 'authorization_code';
var postData = 'grant_type=' + grantType + '&code=' + CODE + '&client_id=' + clientId + '&client_secret=' + clientSecret + '&redirect_uri=' + encodeURIComponent(redirectUri);
const url = 'https://api.amazon.com/auth/o2/token';
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
xhr.onload = (event) => {
let response = xhr.response;
response = JSON.parse(xhr.response);
const isObject = response instanceof Object;
const errorDescription = isObject && response.error_description;
if (errorDescription) {
const error = new Error(errorDescription);
console.log(error);
return reject(error);
}
const token = response.access_token;
const refreshToken = response.refresh_token;
const tokenType = response.token_type;
const expiresIn = response.expiresIn;
//this.setToken(token)
//this.setRefreshToken(refreshToken)
//this.emit(AVS.EventTypes.LOGIN)
console.log('abhi avs.js Logged in.');
resolve(response);
};
xhr.onerror = (error) => {
this._log(error);
reject(error);
};
xhr.send(postData);
});
}
你的代码不干净。我不能说它有用。。但首先,我建议改变
xhr.response
到
当你打电话给promise时,我总是建议你通过chaincatch来完成它,因为你可能会丢失错误
“严格使用”;
var XMLHttpRequest=require(“XMLHttpRequest”).XMLHttpRequest;
var clientId=“amzn1.application-oa2-client.775a44579eaf461b92db3d1a4cb23a5a”;
var deviceId=“测试设备1”;
var设备序列号=123;
var redirectUri=”https://localhost:9745/authresponse";
var Urlcode=“ANcUMLaDrkMtCwUSrIqc”;
var clientSecret=“29a6520d97d11d640e030786e133ccec9ead67005aaa45c212e72e10b00900ff”;
getTokenFromCode(Urlcode)
.然后(函数(结果){
控制台日志(结果);
})
.catch(函数(错误){
console.log(错误);
});
函数getTokenFromCode(代码){
返回新承诺((解决、拒绝)=>{
如果(代码类型!=='string'){
const error=new TypeError('code'必须是字符串');
此._日志(错误);
返回拒绝(错误);
}
const grantType='授权\代码';
var postData='grant_type='+grantType+'&code='+code+'&client_id='+clientId+'&client_secret='+clientSecret+'&redirect_uri='+encodeURIComponent(redirectUri);
常量url=https://api.amazon.com/auth/o2/token';
const xhr=new XMLHttpRequest();
xhr.open('POST',url,true);
setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8');
xhr.onload=()=>{
让response=xhr.responseText;
控制台日志(响应);
response=JSON.parse(response);
常量isObject=对象的响应实例;
const errorDescription=isObject&&response.error_description;
如果(错误描述){
常量错误=新错误(错误描述);
console.log(错误);
返回拒绝(错误);
}
const token=response.access\u token;
const refreshttoken=response.refresh\u令牌;
const tokenType=response.token_type;
const expiresIn=response.expiresIn;
this.setToken(令牌)
this.setRefreshToken(refreshToken)
this.emit(AVS.EventTypes.LOGIN)
决心(回应);
};
xhr.onerror=(错误)=>{
此._日志(错误);
拒绝(错误);
};
发送(postData);
});
}
将代码分解为再现问题的最小部分。99%的可能性是你自己会发现问题。我做了一些改变,就像你说的那样,结果没有改变。它仍然给出相同的错误。当使用nodejs从终端运行js fole时,使用XMLHttpRequest可以吗?添加了完整的代码,我在响应中收到“错误:请求具有无效的授权参数:代码”为了更好地理解,我共享的代码是压缩版本。这是完整的代码。我已经用完整的代码更新了这个问题。请检查一下。@Abhishek-我已经回答了。将xhr.response更改为xhr.responseText
xhr.response
xhr.responseText;