我想知道如何在有效负载中传递json请求,例如:{'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();
答案 0 :(得分:87)
使用request模块
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)
})
答案 1 :(得分:2)
只需转换为字符串并发送。
post_req.write(JSON.stringify(post_data));
答案 2 :(得分:2)
我尝试了这个,它似乎正在工作。我需要基本的身份验证,所以我已经包含了auth,如果你不需要它,你可以丢弃它。
var value = {email:"",name:""};
var options = {
url: 'http://localhost:8080/doc/',
auth: {
user: username,
password: password
},
method :"POST",
json : value,
};
request(options, function (err, res, body) {
if (err) {
console.dir(err)
return
}
console.dir('headers', res.headers)
console.dir('status code', res.statusCode)
console.dir(body)
});