简体   繁体   English

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

[英]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'} : 我想知道,如何在有效负载中传递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();

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

只需转换为字符串并发送。

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

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. 我试过这个似乎工作。我需要基本的身份验证,所以我已经包含了auth,如果你不需要它,你可以丢弃它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM