【问题标题】:How to send http post call from node server?如何从节点服务器发送 http post 调用?
【发布时间】:2018-07-01 21:16:39
【问题描述】:

我正在尝试使用以下数据在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();

我是不是少了什么东西?

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

【问题讨论】:

    标签: node.js post


    【解决方案1】:

    我建议您使用request 模块来简化操作。

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

    【讨论】:

    • 感谢您的回复。工作但出现错误:[错误:无效协议:null]
    • 代理问题
    • 尝试设置你的 npm 配置代理
    • 是的,一些 API 返回 200, 201 以获得成功结果
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-07-14
      • 2021-08-04
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 2019-10-30
      • 1970-01-01
      • 2016-10-27
      相关资源
      最近更新 更多