Node.js https.post request
Node.js https.post request
我使用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()
方法转发它。
'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();
相关文章:
- node js post request.body undefined
- curl post request jquery equivalent
- 如何在 jquery post request 中发送api_key和api_secret参数
- Angular 2:HTTP Post Request,带有URL参数和正文类型参数
- 如何使用包含选项的request.js发出POST请求
- Ajax request Post Params
- 无法读取属性'用户名'对于Angular Post Request,共个未定义
- jQuery POST Ajax request
- jQuery - 在 post request 中传递数组
- 如何在 NodeJS 中传递响应参数,包括来自 POST http.request 的正文
- 在 AJAX post request 中使用自定义 HttpServletRequest 过滤器
- 没有来自 OpenLayers.Request.Post 的 XMLDocument
- HTTP post request - AngularJS 和 JQuery 之间的区别
- React Native Post Request via Fetch throws Network Request F
- 用请求承诺替换节点request.post
- Dojo.request.post-返回的promise说"拒绝”;,但服务器似乎已经接受了请求
- return request method = GET but i send request = POST (ajax)
- AngularJS Http Post Error: Unexpected request: POST
- Promise跳出中的request.post方法
- 如何对多个键使用request.POST.get()