首页 > 解决方案 > 核心 https 库与 npm 'request' 库

问题描述

尝试使用内置节点 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.jshttpsrequest

解决方案


当使用本机httphttps模块时,您需要使用 querystring 模块来字符串化您的正文。

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 正文时在内部执行此操作


推荐阅读