You can use the built-in http module in node, or use a third-party package such as request.
HTTP
An example of using the built in http module e.g:
// The 'https' module can also be used
const http = require('http');
// Example route
app.get('/some/api/endpoint', (req, res) => {
http.get('http://someapi.com/api/endpoint', (resp) => {
let data = '';
// Concatinate each chunk of data
resp.on('data', (chunk) => {
data += chunk;
});
// Once the response has finished, do something with the result
resp.on('end', () => {
res.json(JSON.parse(data));
});
// If an error occured, return the error to the user
}).on("error", (err) => {
res.json("Error: " + err.message);
});
});
Request
Alternatively, a third party package such as request can be used.
First install request:
npm install -s request
And then change your route to something like this:
const request = require('request');
// Example route
app.get('/some/api/endpoint', (req, res) => {
request('http://someapi.com/api/endpoint', (error, response, body) => {
if(error) {
// If there is an error, tell the user
res.send('An erorr occured')
}
// Otherwise do something with the API data and send a response
else {
res.send(body)
}
});
});