【问题标题】:Node.js https.post request [duplicate]Node.js https.post 请求 [重复]
【发布时间】:2015-10-14 20:48:11
【问题描述】:

我正在使用 Node.js,我需要向外部服务器发送一个包含特定数据的 POST 请求。我用 GET 做同样的事情,但这要容易得多,因为我不必包含额外的数据。所以,我的工作 GET 请求看起来像:

var options = {
    hostname: 'internetofthings.ibmcloud.com',
    port: 443,
    path: '/api/devices',
    method: 'GET',
    auth: username + ':' + password
};
https.request(options, function(response) {
    ...
});

所以我想知道如何对 POST 请求做同样的事情,包括以下数据:

type: deviceType,
id: deviceId,
metadata: {
    address: {
        number: deviceNumber,
        street: deviceStreet
    }
}

谁能告诉我如何将这些数据包含在上述选项中?提前致谢!

【问题讨论】:

    标签: javascript node.js http post request


    【解决方案1】:

    在选项对象中,您可以像在 GET 请求中一样包含请求选项,并在您的 POST 正文中再创建一个包含您想要的数据的对象。您使用 querystring 函数(需要由 npm install querystring 安装)将其字符串化,然后使用 https.request() 的 write() 和 end() 方法转发它。

    请务必注意,您需要在选项对象中添加两个额外的标头才能发出成功的发布请求。这些是:

    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': postBody.length
    

    所以您可能需要在 querystring.stringify 返回后初始化您的选项对象。否则你将不知道字符串化的正文数据的长度。

    var querystring = require('querystring')
    var https = require('https')
    
    
    postData = {   //the POST request's body data
       type: deviceType,
       id: deviceId,
       metadata: {
          address: {
             number: deviceNumber,
             street: deviceStreet
          }
       }            
    };
    
    postBody = querystring.stringify(postData);
    //init your options object after you call querystring.stringify because you  need
    // the return string for the 'content length' header
    
    options = {
       //your options which have to include the two headers
       headers : {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': postBody.length
       }
    };
    
    
    var postreq = https.request(options, function (res) {
            //Handle the response
    });
    postreq.write(postBody);
    postreq.end();
    

    【讨论】:

      猜你喜欢
      • 2013-10-02
      • 2018-06-07
      • 1970-01-01
      • 2016-09-27
      • 2017-04-01
      • 2017-04-14
      • 2019-01-18
      • 2012-06-19
      • 1970-01-01
      相关资源
      最近更新 更多