Node.js https.post request

Node.js https.post request

本文关键字:request post https js Node      更新时间:2023-09-26

我使用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
    }
}

谁能告诉我如何将这些数据包含到上面的选项中?提前感谢!

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

重要的是要注意,你需要两个额外的头在你的选项对象,以使一个成功的post请求。这些是:
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postBody.length

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

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();