2017-03-23 33 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,你釘了它:-) –

相關問題