如何 "pass forward" 一个 post() 请求到另一个 api ,获取资源并将其发回?

How to "pass forward" a post() req to another api , get the res and send it back?

背景: 我正在构建一个系统,该系统使用 2 个不同的第 3 方来做某事。 第 3 方 #1 - 是 facebook 信使应用程序,它需要一个 webhook 来连接并通过 POST() 协议发送信息。 第 3 方 #2 - 是我用来构建机器人的平台(称为 GUPSHUP)。

我的服务器位于它们之间 - 因此,我需要将 Facebook Messenger 应用程序连接到我的服务器上的端点(已经这样做),因此 Facebook 应用程序收到的每条消息都会发送到我的服务器。

现在,我真正需要的是我的服务器充当 "middleware" 并简单地将 "req" 和 "res" 发送到另一个平台 url (我们称之为 GUPSHUP-URL),获取资源并将其发送到 Facebook 应用程序。

我不确定如何编写这样的中间件。 我的服务器 post 函数是:

    app.post('/webhook', function (req, res) {
/* send to the GUPSHUP-URL , the req,res which I got ,
   and get the update(?) req and also res so I can pass them
   back like this (I think) 
   req = GUPSHUP-URL.req
   res = GUPSHUP-URL.res
   
*/

});

是的,您可以使用请求模块在另一台服务器上传递 do 请求

var request = require('request');

app.post('/webhook', function (req, res) {
    /* send to the GUPSHUP-URL , the req,res which I got ,
       and get the update(?) req and also res so I can pass them
       back like this (I think) 
       req = GUPSHUP-URL.req
       res = GUPSHUP-URL.res

       */

       request('GUPSHUP-URL', function (error, response, body) {
        if(error){

             console.log('error:', error); // Print the error if one occurred 
             return res.status(400).send(error)
           }
            console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received 

              console.log('body:', body); // Print the HTML for the Google homepage. 
              return res.status(200).send(body); //Return to client
            });

     });

第二版

var request = require('request');


//use callback function to pass uper post
function requestToGUPSHUP(url,callback){

 request(url, function (error, response, body) {

  return callback(error, response, body);
}

app.post('/webhook', function (req, res) {
    /* send to the GUPSHUP-URL , the req,res which I got ,
       and get the update(?) req and also res so I can pass them
       back like this (I think) 
       req = GUPSHUP-URL.req
       res = GUPSHUP-URL.res

       */

       requestToGUPSHUP('GUPSHUP-URL',function (error, response, body) {

        if(error){

          return res.status(400).send(error)
        }

          //do whatever you want


          return res.status(200).send(body); //Return to client
        });


     });

更多信息Request module