【问题标题】:Core https library vs. npm 'request' library核心 https 库与 npm 'request' 库
【发布时间】:2019-08-30 10:55:14
【问题描述】:

我在尝试使用内置节点 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】:

    当使用原生 http 或 https 模块时,您需要使用 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 主体时在内部执行此操作

    【讨论】:

    • 谢谢!实际上,我之前在以前的实现中已经这样做过,但忘记阅读我自己的笔记。你能解释一下为什么它需要 queryString 和 JSON.stringify 吗?
    • 不幸的是它没有帮助。即使这样做,我仍然遇到我请求的服务器问题
    • 我必须在标题中使用这个内容类型才能让它工作你知道为什么:'application/x-www-form-urlencoded',
    • 我不确定。在更改查询字符串之后但在更改内容类型之前,您遇到了什么样的错误?
    猜你喜欢
    • 1970-01-01
    • 2017-05-24
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 2010-10-24
    相关资源
    最近更新 更多