Node.js 核心https库与npm';请求';图书馆

Node.js 核心https库与npm';请求';图书馆,node.js,https,request,Node.js,Https,Request,在尝试使用内置节点https库时,我遇到了一个非常奇怪的问题 请求标头: let requestDetails = { hostname: 'api.domain.com', method: 'POST', path: '/endpointIWant/goHere headers: { 'Client-ID': clientId, 'Content-Type': 'application/json', Authorizati

在尝试使用内置节点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上使用流行的“请求”库时,它工作得很好,我得到了预期的响应

这导致人们相信这两个库之间的请求的“编码”或“分块”可能有所不同,但我不知道是什么

是否有人拥有节点https库的经验并了解其中的任何问题


我更喜欢尽可能多地使用内置库来保持我的包的小尺寸

当使用本机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
    },
  };


“请求”构建在本机模块之上,当您向其传递json正文时,它会在内部执行此操作

谢谢!在以前的实现中,我实际上已经这样做了,但是忘记阅读我自己的注释。你能解释一下为什么它需要queryString和JSON.stringify吗?不幸的是,它没有帮助。即使这样做,我仍然会遇到Im请求的服务器问题。我必须在标题中使用此内容类型才能使其正常工作。您知道为什么吗?'application/x-www-form-urlencoded',我不确定。在更改querystring之后但在更改内容类型之前,您遇到了什么样的错误?