首页 文章

向外部api发布请求

提问于
浏览
0

在来自angularjs的ajax调用的post请求之后,我想将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的响应..

感谢您的帮助和想法:)

2 回答

  • 1

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

    试试这个,

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

相关问题