Background: I am using building a system which uses 2 different 3rd parties to do something. 3rd party #1 - is facebook messenger app, which requires a webhook to connect and send info via POST() protocol. 3rd party #2 - is a platform which I used to build a bot (called GUPSHUP).
My server is in the middle between them - so, I need to hook the facebook messenger app to my endpoint on MY server (already did), so every message that the Facebook app get's, it sends to MY server.
Now, what I actually need, is that my server to act as "middleware" and simply send the "req" and "res" it gets to the other platform url (let's call it GUPSHUP-URL), get the res back and send it to the Facebook app.
I am not sure how to write such a middleware that acts like this. My server post function is:
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
*/
});
Yes , you can pass do request on another server using request module
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
});
});
2nd Version
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
});
});
More info Request module