2016-09-28 46 views
2

我曾试图在https://api-mean.herokuapp.com/api/contacts发送后电话与以下数据:如何从节点服务器发送http post call?

{ 
    "name": "Test", 
    "email": "[email protected]", 
    "phone": "989898xxxx" 
} 

但没有得到任何回应。 我也试过它与邮递员工作正常。我已经在邮递员的回复。

我使用下面的代码的NodeJS:

 var postData = querystring.stringify({ 
      "name": "Test", 
      "email": "[email protected]", 
      "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(); 

上午我缺少点什么?

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

回答

0

要发送的NodeJS从HTTP-POST调用,您可能需要使用request module

样品:

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

我建议你使用request模块,使事情变得更容易。

var request=require('request'); 

    var json = { 
    "name": "Test", 
    "email": "[email protected]", 
    "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); 
    } 
    }); 
+0

感谢您的回复。 工作,但得到错误:** [错误:无效协议:空] ** –

+0

有一些代理问题 – abdulbarik

+0

http://stackoverflow.com/questions/34964935/node-js-request-module-giving-error -for-http-call-error-invalid-protocol-null – abdulbarik

相关问题