简体   繁体   English

Node.js HTTPS.get 返回状态码 406

[英]Node.js HTTPS.get returns a status code 406

I'm trying to make a promise-ified HPPTS request to an API, using only the built in HTTPS module.我正在尝试仅使用内置的 HTTPS 模块向 API 发出承诺化的 HPPTS 请求。 The returned status code is 406, and I'm also getting a buffer error:返回的状态代码是 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)

Here's my function:这是我的功能:

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

At the response end, the responseText is just a single space.在响应端, responseText 只是一个空格。

So what am I doing wrong here?那么我在这里做错了什么? Thank you for the help and patience.感谢您的帮助和耐心。

EDIT: Also worth noting, if I change the Buffer.concat line to var responseString = responseBuffer.join();编辑:另外值得注意的是,如果我将 Buffer.concat 行更改为 var responseString = responseBuffer.join(); the error becomes this, on the callback(JSON.parse(responseString));错误变成这个,在回调(JSON.parse(responseString)); line.线。

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)

It looks like there are 2 separate problems:看起来有两个不同的问题:

  • When you call response.setEncoding('utf8') , node automatically converts the incoming data into strings.当您调用response.setEncoding('utf8') ,节点会自动将传入的数据转换为字符串。 This means that the data event fires with strings, not Buffer s.这意味着data事件是用字符串触发的,而不是Buffer

    This means you either need to keep the stream in binary mode (by not calling setEncoding ), keep the array of buffers, and then concatenate and convert them to a string at the end.这意味着您要么需要将流保持在二进制模式(通过不调用setEncoding ),保留缓冲区数组,然后将它们连接起来并在最后转换为字符串。

     response.on('end', function() { try { var responseString = Buffer.concat(responseBuffer).toString('utf8'); resolve(JSON.parse(responseString)); } catch(ex) { reject(ex); } });

    ...or keep the setEncoding call and do simple string concatenation. ...或保留setEncoding调用并进行简单的字符串连接。

     response.on('data', function(str) { responseString += str; });

    I recommend the former for better performance (node has to do some internal buffering to deal with multibyte characters in streaming mode).我推荐前者以获得更好的性能(节点必须做一些内部缓冲来处理流模式下的多字节字符)。

  • The API you're using is returning a 406 ( Not Acceptable ).您使用的 API 返回 406 ( Not Acceptable )。 This likely means you must supply an Accept header in your request.这可能意味着您必须在请求中提供Accept标头。

Based on the following doc, Buffer.concat needs List of Buffer or Uint8Array as parameter基于以下文档,Buffer.concat 需要List of Buffer or Uint8Array作为参数

https://nodejs.org/api/buffer.html#buffer_class_method_buffer_concat_list_totallength https://nodejs.org/api/buffer.html#buffer_class_method_buffer_concat_list_totallength

You can try something like the following to convert the string to buffer before push it to your array.在将字符串推送到数组之前,您可以尝试类似以下操作将字符串转换为缓冲区。

response.on('data', function(d) {
    responseBuffer.push(Buffer.from(d, 'utf8'));
});

Check the detailed issue here检查详细问题here

https://github.com/nodejs/node/issues/4949 https://github.com/nodejs/node/issues/4949

Hope it helps希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM