【发布时间】:2017-09-04 14:57:44
【问题描述】:
我可以使用来自 curl 的 Authorization 标头发出 GET 请求,但不能来自 Node.js 中的 request 或 https。服务器使用 curl 返回状态 200,但使用 request 或 https 返回状态 500。来自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
})
在不使用request.js 的情况下使用https 也会失败:
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' } } }
【问题讨论】:
-
500 internal error 一般表示服务器端有错误。你检查过 API 服务器日志吗?它是否试图解析“User-Agent”标头?
-
好问题。我无权访问服务器,只有 OAuth 路由。 curl 或 request 是否传递了
User-Agent标头? -
Curl 通过一个,除非你指定,否则我认为 request 不会。
-
@NehalJWani 谢谢!!那是我需要的线索。 curl 提供额外的标题。将
--verbose添加到 curl 中,我看到其中之一是"Accept: */*"并将其添加到请求中使其工作。只是为了好玩和形式,请写下我可以接受的答案。 -
我已将其添加为答案。
标签: node.js curl https requestjs