I'm trying to create a backend that sends a GET request to another API.
For example:
My API: localhost:3000/
Route: /getdata/data1
Other API: api.com/target/data
(This is a fake URL, just assume that this route has the data that I want)
How can I send a get request to that API from my API? Ajax.get?
You can use the built-in http module in node, or use a third-party package such as request.
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);
});
});
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)
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With