request.js失败,其中CURL通过授权标头成功获取GET请求

我可以使用curl的Authorization头进行GET请求,但不能使用Node.js中的requesthttps进行request 。 服务器使用curl返回状态200,使用requesthttps返回500。 来自requesthttps request可能与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' } } } 

500内部错误通常意味着在服务器端存在错误。 所以,理想情况下,你应该看看服务器日志。

但是,如果您无法访问这些日志,请查看您尝试的每个选项发送的请求之间的差异:

模块:请求(手动指定的auth头文件):

 GET /path/to/resource HTTP/1.1 Authorization: Bearer abc123def456 host: api.domain.com 

模块:请求(具有明确指定的auth头):

 GET /path/to/resource HTTP/1.1 host: api.domain.com authorization: Bearer abc123def456 

模块:HTTP(手动指定validation标题):

 GET /path/to/info HTTP/1.1 Authorization: Bearer abc123def456 Host: api.domain.com 

curl:

 GET /path/to/resource HTTP/1.1 Host: api.domain.com User-Agent: curl/7.51.0 Accept: */* Authorization: Bearer abc123def456 

很明显,其余的模块不发送HTTP头 '用户代理'和'接受'。 所以,在服务器上运行的应用程序可能会试图parsing至less一个和失败。