以下curl请求正常工作,返回身份验证令牌
curl POST -s -d "grant_type=password&username=someusername&password=somepassword&client_id=someid&client_secret=somesecret&response_type=token" "someurl"
当node.js中的等效请求失败时
let url = someurl
var dataString = 'grant_type=password&username=somename&password=somepassword&client_id=someid&client_secret=somesecret&response_type=token';
var options = {
url: url,
method: 'POST',
body: dataString,
allow_redirects : true
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(error)
console.log(body)
}
request(options, callback);
错误是
{"error":"unauthorized","error_description":"An Authentication object was not found in the SecurityContext"}
这可能只针对此代码。无论如何,差异(默认参数或配置)可以解释这种差异。注意,程序在有和没有allow_redirects选项的情况下都会失败,但是应该允许重定向。
这是在macosx上运行的节点v7.10.0并请求2.81.0
答案 0 :(得分:0)
我的第一个假设是您错过了请求所需的标头
let url = someurl
var dataString = 'grant_type=password&username=somename&password=somepassword&client_id=someid&client_secret=somesecret&response_type=token';
var options = {
url: url,
method: 'POST',
body: dataString,
headers: { 'content-type': 'application/x-www-form-urlencoded' },
allow_redirects: true
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(error)
console.log(body)
}
request(options, callback);
如果这不正确,请告诉我,我会解决问题