将请求发布到外部API

时间:2018-02-12 14:58:29

标签: node.js express

在angularjs中的ajax调用发出请求之后,我想将angularjs中的请求参数发送到外部api。我得到了我想要的所有参数。但我不知道,我如何在我的nodejs url中向api发出新的帖子请求。我需要这一步到nodejs。

这是我的代码

router.post({
      url: '/user/:id/sw'
    }, (req, res, next) => {


      var userId = req.pramas.id;
      var firstName = req.pramas.firstName;
      var lastName = req.pramas.lastName;




      var data = 'test';

      res.send(200, data);
    });

我发现了一些像这样的解决方案:(只是示例代码)

  request({
    uri: 'http://www.giantbomb.com/api/search',
    qs: {
      api_key: '123456',
      query: 'World of Warcraft: Legion'
    },
    function(error, response, body) {
      if (!error && response.statusCode === 200) {
        console.log(body);
        res.json(body);
      } else {
        res.json(error);
      }
    }
  });

但这不起作用。如何使用req.params向外部api发出新的Post请求?我也需要来自api的响应..

感谢您的帮助和想法:)

3 个答案:

答案 0 :(得分:2)

req.params 不是req.pramas

试试这个

var request = require('request');
router.post({
    url: '/user/:userId/shopware'
}, (req, res, next) => {
    var params = req.params;
    request.get({
        uri: 'http://www.giantbomb.com/api/search',
        qs: params // Send data which is require
    }, function (error, response, body) {
        console.log(body);
    });
});

答案 1 :(得分:1)

试试这个,



const request = require('request-promise')
const options = {
  method: 'POST',
  uri: 'http://localhost.com/test-url',
  body: {
    foo: 'bar'
  },
  json: true 
    // JSON stringifies the body automatically
};
​
request(options)
  .then(function (response) {
    // Handle the response
  })
  .catch(function (err) {
    // Deal with the error
  })




答案 2 :(得分:0)

var request = require("request");

exports.checkstatus =异步(req,res)=> {//这是您可以删除的功能行

try {
 var options = { 
    method: 'POST',
    url: 'https://mydoamin/api/order/status',
    headers: 
    { 
        signature: '3WHwQeBHlzOZiEpK4yN8CD',
        'Content-Type': 'application/json' 
    },
    body: 
    { 
        NAME: 'Vedant',
        ORDERID: 'ORDER_ID1596134490073',
     
    },
    json: true 
};

request(options, function (error, response, body) {
if (error) throw new Error(error);

    console.log(body); //get your response here
});

} catch (error) {
    return fail(res, error.message);
}

};