I wanted to know, how to pass the json request in the payload, for eg: {'name' : 'test', 'value' : 'test'}
:
我想知道,如何在有效负载中传递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();
Thanks for the helps. Prats
谢谢你的帮助。傻瓜
3 个解决方案
#1
74
Use the request module
使用请求模块
npm install -S request
npm安装- s请求
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)
})
#2
2
Just convert to a string and send.
只需转换成字符串并发送。
post_req.write(JSON.stringify(post_data));
#3
0
i tried this and it seems to be working.I needed basic auth so i have included auth,if you don't need it you can discard it.
我试过了,好像有用。我需要基本的授权,所以我包含了授权,如果你不需要,你可以放弃它。
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)
});
#1
74
Use the request module
使用请求模块
npm install -S request
npm安装- s请求
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)
})
#2
2
Just convert to a string and send.
只需转换成字符串并发送。
post_req.write(JSON.stringify(post_data));
#3
0
i tried this and it seems to be working.I needed basic auth so i have included auth,if you don't need it you can discard it.
我试过了,好像有用。我需要基本的授权,所以我包含了授权,如果你不需要,你可以放弃它。
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)
});