2017-03-23 32 views
0

背景: 我正在使用建立一个系统,使用2个不同的第三方来做些事情。 第三方#1 - 是facebook messenger应用程序,它需要webhook通过POST()协议连接和发送信息。 第三方#2 - 是我用来构建bot的平台(称为GUPSHUP)。我的服务器处于它们之间的中间 - 所以,我需要将facebook messenger应用程序挂接到我的服务器上的端点(已经做到了),所以每一条Facebook应用程序获得的消息都会发送到我的服务器。如何将post()req传递给另一个api,获取res并将其发回?

现在,我真正需要的是,我的服务器充当“中间件”,并简单地将“req”和“res”发送到其他平台url(我们称之为GUPSHUP-URL),获取退回并发送到Facebook应用程序。

我不知道如何编写这样的中间件。 我的服务器后功能是:

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 
 
    
 
*/ 
 

 
});

回答

1

是的,你可以使用请求模块

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

+0

Thanks @ Love-Kesh,感谢您的帮助。 对不起,只是为了确保我理解正确 - 你的请求代码应该是 请求('GUPSHUP-URL',函数(error,res,req.body){ if(error){...} /*我如何“返回”res.send(200)到上面的帖子()?*/ }); –

+0

看到我的第二个回答 –

+0

Thanks @ Love-Kesh,你钉了它:-) –

相关问题