Here is the thing :
I have a client which sends data to a server. This server has to contact an external A.P.I. and send back its response to the client. I just can’t figure out how and where I can contact the external A.P.I once the server has got the client data.
I route client data like this :
app.post('/getAutoComplete', routes.read);
routes.read retrieves the data within req.body. With my nodejs version (without express framework), I then request the api this way :
var http = require('http'), options = {
host : "192.168.1.38",
port : 8080,
path : "/myURL",
method : 'POST'
};
var webservice_data = "";
var webservice_request = http.request(options, function(webservice_response)
{
webservice_response.on('error', function(e){ console.log(e.message); });
webservice_response.on('data', function(chunk){ webservice_data += chunk;});
webservice_response.on('end', function(){res.send(webservice_data);});
});
webservice_request.write(req.body);
webservice_request.end();
The problem is that i’d like to use native expressJS method like app.post but I don’t know how because :
- Express (app) object is not available here (declared in app.js but not in the route file)
- I don’t know how to send POST data with app.post
Any suggestion ?
routes.readis a function. You can call it with extra parameters, so for exampleNow make the
routes.readfunction use the first parameter as the query and when it’s gathered the response from the remote API, call the second parameter with any error as the first parameter and the response as the second one.Update This answer has already been picked as an answer, but it’d be more helpful if I showed an example of routes.read, too: