我应该如何在http post请求的有效载荷中传递json数据

我想知道,如何在有效载荷中传递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(); 

感谢您的帮助。 普拉茨

使用请求模块

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) }) 

只需转换为一个string并发送。

 post_req.write(JSON.stringify(post_data));