我可以从 Node.js 发出带有 Authorization 标头的 GET 请求,curl
但不能来自Node.jsrequest
或https
在 Node.js 中。服务器使用 curl 返回状态 200,但使用request
or返回 500 https
。呼叫可能来自request
或https
不同curl
?服务器如何以不同的方式读取它们?
以下 cURL 从命令行成功:
curl -H "Authorization: Bearer abc123def456" https://api.domain.com/path/to/resource
但是相同的请求在 Node 中使用 request.js 失败
var options = {
type: 'get',
url: "https://api.domain.com/path/to/resource",
headers: {
"Authorization": " Bearer abc123def456"
}
}
request(options, function (err, response, body) {
assert.equal(response.statusCode, 200) ; // 500 internal error
})
使用该auth
选项的 request.js 也会失败:
var options = {
type: 'get',
url: "https://api.domain.com/path/to/resource",
auth: {
"bearer": "abc123def456"
}
}
request(options, function (err, response, body) {
assert.equal(response.statusCode, 200) ; // 500 internal error
})
https
不使用时也会失败request.js
:
var options = {
host: 'api.domain.com',
port: 443,
path: '/path/to/info',
method: 'GET',
headers: {
"Authorization": " Bearer abc123def456"
}
}
var req = https.request(options, function (res) {
res.setEncoding('utf8');
res.on('end', function () {
assert.equal(res.statusCode, 200) // 500 internal error
})
});
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
});
req.end();
但是如果从 Node 中退出,curl 请求会成功:
exec("curl -H "Authorization: Bearer abc123def456" https://api.domain.com/path/to/resource", function (error, stdout, stderr) {
var obj = JSON.parse(stdout) // successfully retrieved and parsed
});
request-debug
提供以下信息:
{ request:
{ debugId: 1,
uri: 'https://api.domain.com/path/to/resource',
method: 'GET',
headers:
{ host: 'api.domain.com',
authorization: 'Bearer abc123def456' } } }