web-dev-qa-db-ja.com

HTTPポストリクエストのリクエストペイロードで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();
35
Prats

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

文字列に変換して送信するだけです。

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

私はこれを試してみましたが、動作しているようです。基本認証が必要だったので、認証を含めました。不要な場合は破棄できます。

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