我应该如何在http post请求的请求有效负载中传递json数据 [英] How should I pass json data in the request payload of http post request
本文介绍了我应该如何在http post请求的请求有效负载中传递json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何在有效负载中传递json请求,例如: {'name':'test','value':'test'}
:
I wanted to know, how to pass the json request in the payload, for eg: {'name' : 'test', 'value' : 'test'}
:
var post_data = {};
var post_options = {
host: this._host,
path: path,
method: 'POST',
headers: {
Cookie: "session=" + session,
'Content-Type': 'application/json',
'Content-Length': post_data.length,
}
};
// Set up the request
var post_req = http.request(post_options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('========Response========: ' + chunk);
});
});
// post the data
post_req.write(post_data);
post_req.end();
推荐答案
使用请求模块
npm install -S request
var request = require('request')
var postData = {
name: 'test',
value: 'test'
}
var url = 'https://www.example.com'
var options = {
method: 'post',
body: postData,
json: true,
url: url
}
request(options, function (err, res, body) {
if (err) {
console.error('error posting json: ', err)
throw err
}
var headers = res.headers
var statusCode = res.statusCode
console.log('headers: ', headers)
console.log('statusCode: ', statusCode)
console.log('body: ', body)
})
这篇关于我应该如何在http post请求的请求有效负载中传递json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文