2016-09-28 102 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

相關問題