2017-04-09 140 views
2

我可以在Node.js中使用curl授權標頭但不從requesthttps發出GET請求。服務器使用curl返回狀態200,但使用requesthttps返回500。來自requesthttps的呼叫可能與curl有什麼不同?服務器如何以不同的方式讀取它們?request.js失敗,其中CURL成功獲得帶授權標頭的GET請求

以下捲曲從命令行成功:

curl -H "Authorization: Bearer abc123def456" https://api.domain.com/path/to/resource 

但是,同樣的請求將失敗,並在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

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(); 

但捲曲請求成功,如果從節點掏出:

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' } } } 
+0

500內部錯誤通常意味着服務器端存在錯誤。你檢查了API服務器日誌嗎?它試圖解析'User-Agent'頭部嗎? –

+0

偉大的問題。我沒有訪問服務器的權限,只有OAuth路由。捲曲或請求是否通過「User-Agent」標頭? – prototype

+0

捲髮通過一個,我不認爲要求,除非你指定它。 –

回答

2

500 internal error一般意味着是一個錯誤服務器端。所以,理想情況下,您應該查看服務器日誌。

但是,如果你沒有訪問這些日誌,看看由你所嘗試的選項每一個發送的請求之間的區別:

模塊:請求(手工指定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(與手動指定AUTH報頭):

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

捲曲:

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

這是很明顯的是,其餘模塊不發送HTTP headers「用戶代理」和「接受」。因此,運行在服務器上的應用程序可能會試圖解析至少其中一個並失敗。