如何从节点服务器发送http post调用?

我尝试使用以下数据在https://api-mean.herokuapp.com/api/contacts上发送通话:

 { "name": "Test", "email": "test@xxxx.in", "phone": "989898xxxx" } 

但没有得到任何回应。 我也试过邮递员工作正常。 邮递员我得到了回应。

我正在使用以下nodejs代码:

  var postData = querystring.stringify({ "name": "Test", "email": "test@xxxx.in", "phone": "989898xxxx" }); var options = { hostname: 'https://api-mean.herokuapp.com', path: '/api/contacts', method: 'POST', headers: { 'Content-Type': 'application/json' } }; var req = http.request(options, function (res) { var output = ''; res.on('data', function (chunk) { output += chunk; }); res.on('end', function () { var obj = JSON.parse(output.trim()); console.log('working = ', obj); resolve(obj); }); }); req.on('error', function (e) { console.error(e); }); req.write(postData); req.end(); 

我缺less什么东西吗?

如何从节点服务器发送http post调用?

我build议你使用请求模块来使事情更容易。

  var request=require('request'); var json = { "name": "Test", "email": "test@xxxx.in", "phone": "989898xxxx" }; var options = { url: 'https://api-mean.herokuapp.com/api/contacts', method: 'POST', headers: { 'Content-Type': 'application/json' }, json: json }; request(options, function(err, res, body) { if (res && (res.statusCode === 200 || res.statusCode === 201)) { console.log(body); } }); 

对于从nodejs发送HTTP-POST调用,您可能需要使用请求模块

样品:

 var request = require('request'); request({ url: "some site", method: "POST", headers: { // header info - in case of authentication enabled }, json:{ // body goes here }, function(err, res, body){ if(!err){ // do your thing }else{ // handle error } });