How to call an api from another api in expressjs?
Create a common middleware which need to executed for both the routes.
Below is the code snippet for the same:
app.get('/test', test);
app.get('/check', check, test);
check and test are the middlewares which is used in common.
Simple solution is to define a method which can be called using both request routes.
app.get('/test', (req, res) => {
console.log("this is test");
callMeMayBe();
});
callMeMayBe()
{
//Your code here
}
To "call an API from another API", a quick and easy way is sending HTTP request inside Express server, browser would never know an internal HTTP invocation happens, not mention page-redirect. The benefit of this design includes:
- There's no need to change the current API design.
- The API invocation can be made exact like sent from browser.
Here is an example:
var http = require('http');
router.get('/test', function(req, res) {
res.end('data_from_test');
});
router.get('/check', function(req, res) {
var request = http.request({
host: 'localhost',
port: 3000,
path: '/test',
method: 'GET',
headers: {
// headers such as "Cookie" can be extracted from req object and sent to /test
}
}, function(response) {
var data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
res.end('check result: ' + data);
});
});
request.end();
});
The result of GET /check
would be:
check result: data_from_test