Reputation: 59
I started my React project making client-side api calls(which is kind of a big no no). So now I have to implement a backend server proxy. Given this link - https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/huhi?api_key=<MY_API_KEY>
. How do I make api calls with express? I have tried to look at multiple documents/tutorials, but haven't landed any solutions
const app = express();
app.get('/api/customers', (req, res) => {
res.json("https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/huhi?api_key=<MY_API_KEY>");
});
//this ofcourse gives an error
const port = 5000;
app.listen(port, () => console.log(`Server started on port ${port}`))```
Upvotes: 0
Views: 68
Reputation: 708056
You don't use Express for that - Express is for receiving requests (on your server), not sending requests. You use one of these libraries for making http requests to an external server. My personal favorite is got() because I like the programming interface and it has worked well for me, but all the libraries in that link above work just fine. Pick the one that appeals to you.
You can even use http.request()
or http.get()
which are built-into the http module in nodejs, but they are lower level than the libraries I've listed and you will have to write more code yourself, even to just make a simple http request and get the response.
If all you want to do is to make a request of another server and just send it's response to the original incoming http request, then you can use stream.pipeline()
for that:
const stream = require('stream');
const got = require('got');
app.get('/api/customers', (req, res) => {
const url = "https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/huhi?api_key=<MY_API_KEY>";
stream.pipeline(got.stream(url), res, err => {
if (err) {
console.log(err);
res.sendStatus(500);
}
});
});
Upvotes: 0
Reputation: 311
Express is used to create servers. There are various other packages in Node that can help you make API calls. Some of them are Axios, Got, Superagent, and many more. You can even use the HTTP standard library to make API calls.
I would recommend using Axios as it is easy to use, you can find its documentation here.
Upvotes: 2