Nho*_*hor 5 javascript post http request node.js
我正在使用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) {
...
});
Run Code Online (Sandbox Code Playgroud)
所以我想知道如何用POST请求做同样的事情,包括如下数据:
type: deviceType,
id: deviceId,
metadata: {
address: {
number: deviceNumber,
street: deviceStreet
}
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我如何将这些数据包含在上面的选项中?提前致谢!
小智 7
在options对象中,您可以像在GET请求中一样包含请求选项,并在POST的正文中再创建一个包含所需数据的对象.您使用查询字符串函数(您需要安装它npm install querystring)对其进行字符串化,然后使用https.request()的write()和end()方法转发它.
请务必注意,您的选项对象中需要两个额外的标头才能成功发布请求.这些是 :
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postBody.length
Run Code Online (Sandbox Code Playgroud)
所以你可能需要在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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21493 次 |
| 最近记录: |