Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

javascript - How should I pass json data in the request payload of http post request

I wanted to know, how to pass the json request in the payload, for eg: {'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();
question from:https://stackoverflow.com/questions/16188137/how-should-i-pass-json-data-in-the-request-payload-of-http-post-request

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the request module

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...