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

我想知道,如何在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-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();

最佳答案

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

https://stackoverflow.com/questions/16188137/

相关文章:

json - 如何强制将请求正文解析为纯文本而不是 Express 中的 json?

ios - 如何使用 SwiftyJSON 遍历 JSON?

java - 使用 GSON 解析 JSON 文件

java - Jersey 异常 : SEVERE: A message body reader f

json - 如何在 Mac 上通过命令行安装 JQ?

java - 用于生成和使用 JSON 的 Controller 的 Spring RequestM

c# - 将对象序列化为 JSON 时循环引用检测到异常

java - Jackson JSON 字段映射大小写?

ios - waitUntilAllTask​​sAreFinished 错误 Swift

javascript - Javascript对象和JSON对象有什么区别