Javascript 如何在http post请求的请求负载中传递json数据
我想知道如何在负载中传递json请求,例如:Javascript 如何在http post请求的请求负载中传递json数据,javascript,json,node.js,payload,Javascript,Json,Node.js,Payload,我想知道如何在负载中传递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-Le
{'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安装-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)
})
只需转换为字符串并发送
post_req.write(JSON.stringify(post_data));
我试过这个,它似乎是工作。我需要基本的授权,所以我已经包括了授权,如果你不需要它,你可以放弃它
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)
});
这回答了你的问题吗?我想在这里跟你核实一下。“body:postData”是正确的还是应该像“body:JSON.stringify(postData)”那样对postData进行字符串化?thx.@Noah如果我想使用
request.post(…)
,这会发生什么变化?客户端应用程序(Electron应用程序)将发送的大多数请求都包含基于JSON的主体,唯一的例外是多部分主体。在Express(服务器端)应用程序中,我很难找到正确的方法来使用这个库和bodyParser
设置。我使用app.use(bodyParser.json())
和app.use(bodyParser.urlencoded({extended:true}))代码>和请求解析失败,直到我将extended
更改为false。我不确定这与JSON请求有什么关系,这是造成我困惑的原因。@Ric通常您是对的,但是添加JSON:true
可以让请求知道它应该在发送之前对负载进行字符串化。