如何从节点服务器发送http发布呼叫? [英] How to send http post call from node server?

查看:94
本文介绍了如何从节点服务器发送http发布呼叫?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have trying to send post call on https://api-mean.herokuapp.com/api/contacts with following data:

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

但没有得到任何回应. 我也尝试过与邮递员一起使用,效果很好.我在邮递员那里得到回应.

But not get any response. I have also tried it with postman it working fine. I have get response in postman.

我正在使用以下nodejs代码:

I am using following nodejs code:

        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帖子呼叫?

How to send http post call from node server?

推荐答案

我建议您使用请求使事情变得更容易的模块.

I recommend you to use the request module to make things easier.

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

这篇关于如何从节点服务器发送http发布呼叫?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆