核心https库与npm'请求'库

问题描述 投票:0回答:1

尝试使用内置节点https库时,我遇到了一个非常奇怪的问题。

请求标题:

  let requestDetails = {
    hostname: 'api.domain.com',
    method: 'POST',
    path: '/endpointIWant/goHere
    headers: {
      'Client-ID': clientId,
      'Content-Type': 'application/json',
      Authorization: bearerToken
    },
  };

请求机构:

 let body = JSON.stringify({
    "content_type": "application/json",
     "message" : message
  });

这是我使用默认的https节点库的标准调用:

 let req = https.request(requestDetails, function (res){

    let responseBody = undefined;

    res.on('body', function(res) {
      responseBody = '';
    });

    res.on('data', function(chunk) {
      responseBody += chunk;
    });

    res.on('end', function() {
      console.log(responseBody);
    });
  });

  req.write(body);

  req.on('error', function(e) {
    console.log(e);
  });

  req.end();

现在每当我将此请求发送到相关服务器时,我得到一个:

Your browser sent a request that this server could not understand.
Reference #7.24507368.1554749705.3185b29b

然而,当我在NPM上使用流行的“请求”库时,它工作正常,我得到了我期望的响应。

这导致相信这两个库之间的请求的“编码”或“分块”可能有所不同,但我无法弄清楚是什么。

有没有人有Node https库的经验,并了解那里的任何问题?

我更喜欢尽可能使用内置库来保持我的包大小。

node.js https request
1个回答
1
投票

使用本机http或https模块时,您需要使用查询字符串模块来对您的身体进行字符串化。

const querystring = require('querystring');

let body = querystring.stringify({
    "content_type": "application/json",
    "message" : message
});

//also include the content length of your body as a header

let requestDetails = {
    hostname: 'api.domain.com',
    method: 'POST',
    path: '/endpointIWant/goHere
    headers: {
      'Client-ID': clientId,
      'Content-Type': 'application/json',
      'Content-Length' : body.length
      Authorization: bearerToken
    },
  };

'request'建立在原生模块之上,当你传递一个json体时,它会在内部完成

© www.soinside.com 2019 - 2024. All rights reserved.