node.js 我应该如何在 http post 请求的请求负载中传递 json 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16188137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:18:03  来源:igfitidea点击:

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

javascriptjsonnode.jspayload

提问by Prats

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

回答by Noah

Use the requestmodule

使用请求模块

npm install -S 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)
})

回答by jemiloii

Just convert to a string and send.

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

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

回答by Alien

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.

我试过了,它似乎在工作。我需要基本身份验证,所以我已经包含了身份验证,如果你不需要它,你可以丢弃它。

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