Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Node.js https.post请求_Javascript_Node.js_Http_Post_Request - Fatal编程技术网

Javascript Node.js https.post请求

Javascript Node.js https.post请求,javascript,node.js,http,post,request,Javascript,Node.js,Http,Post,Request,我正在使用Node.js,需要向外部服务器发送包含特定数据的POST请求。我在GET上也做了同样的事情,但这要容易得多,因为我不必包含额外的数据。因此,我的工作GET请求如下所示: var options = { hostname: 'internetofthings.ibmcloud.com', port: 443, path: '/api/devices', method: 'GET', auth: username + ':' + password

我正在使用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请求中一样包含请求选项,并在帖子正文中创建一个包含所需数据的多个对象。您可以使用querystring函数(需要通过
npm install querystring
安装querystring)将其字符串化,然后使用https.request()的write()和end()方法转发它

重要的是要注意,为了发出成功的post请求,您需要在options对象中添加两个额外的头。这些是:

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