[英]Node.js HTTPS.get returns a status code 406
我正在嘗試僅使用內置的 HTTPS 模塊向 API 發出承諾化的 HPPTS 請求。 返回的狀態代碼是 406,我也收到了緩沖區錯誤:
TypeError: buf.copy is not a function
at Function.Buffer.concat (buffer.js:240:9)
at IncomingMessage.<anonymous> (/var/task/index.js:562:41)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at nextTickCallbackWith2Args (node.js:437:9)
at process._tickDomainCallback (node.js:392:17)
這是我的功能:
function createRequest(url, body, callback){
return new Promise(function(resolve, reject) {
try{
var parsedUrl = Url.parse(url, true, true);
}
catch(e) {
console.log("URL parsing error");
}
try{
https.get({
hostname: parsedUrl.hostname,
path: parsedUrl.path,
headers: {
'Content-Type': 'application/json'
}
}, function(response) {
console.log(response.statusCode);
response.setEncoding("utf8");
var responseBuffer = [];
response.on('data', function(d) {
responseBuffer.push(d);
});
response.on('end', function() {
var responseString = Buffer.concat(responseBuffer);
callback(JSON.parse(responseString));
resolve(responseString);
});
response.on('error', (e) => {
reject(e);
});
});
} catch(e){
console.log(e);
}
});
}
在響應端, responseText 只是一個空格。
那么我在這里做錯了什么? 感謝您的幫助和耐心。
編輯:另外值得注意的是,如果我將 Buffer.concat 行更改為 var responseString = responseBuffer.join(); 錯誤變成這個,在回調(JSON.parse(responseString)); 線。
SyntaxError: Unexpected end of input
at Object.parse (native)
at IncomingMessage.<anonymous> (/var/task/index.js:564:27)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at nextTickCallbackWith2Args (node.js:437:9)
at process._tickDomainCallback (node.js:392:17)
看起來有兩個不同的問題:
當您調用response.setEncoding('utf8')
,節點會自動將傳入的數據轉換為字符串。 這意味着data
事件是用字符串觸發的,而不是Buffer
。
這意味着您要么需要將流保持在二進制模式(通過不調用setEncoding
),保留緩沖區數組,然后將它們連接起來並在最后轉換為字符串。
response.on('end', function() { try { var responseString = Buffer.concat(responseBuffer).toString('utf8'); resolve(JSON.parse(responseString)); } catch(ex) { reject(ex); } });
...或保留setEncoding
調用並進行簡單的字符串連接。
response.on('data', function(str) { responseString += str; });
我推薦前者以獲得更好的性能(節點必須做一些內部緩沖來處理流模式下的多字節字符)。
您使用的 API 返回 406 ( Not Acceptable )。 這可能意味着您必須在請求中提供Accept
標頭。
基於以下文檔,Buffer.concat 需要List of Buffer or Uint8Array
作為參數
https://nodejs.org/api/buffer.html#buffer_class_method_buffer_concat_list_totallength
在將字符串推送到數組之前,您可以嘗試類似以下操作將字符串轉換為緩沖區。
response.on('data', function(d) {
responseBuffer.push(Buffer.from(d, 'utf8'));
});
檢查詳細問題here
https://github.com/nodejs/node/issues/4949
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.