I am working on building a website and wish to expand my API functionality. I have a frontend react app and a backend express nodejs server.
I have another local webserver that hosts some data about football matches. Data about the round and year is served by calling /nrl/week={week}&season={year}
.
The react app is currently set up such that axios sends a request to the backend and the backend sends a request to the other webserver.
const data = await axios.get('/nrl')
frontend code
request('http://127.0.0.1:5000/nrl/week=20&season=2022',
backend code
I want to be able to make a request from the front end to the backend specifying what week and season, as currently its hardcoded.
Thanks
CodePudding user response:
Make your request from the front-end with URL query parameters and forward those through to the other API
Front-end
// These will probably come from user selection / input
const week = 20;
const season = 2022;
const { data } = await axios.get("/nrl", {
params: { week, season }
});
Express
app.get("/nrl", async (req, res, next) => {
const queryParams = new URLSearchParams(req.query);
// FYI `request` is deprecated. See https://github.com/request/request/issues/3142
request(
`http://127.0.0.1:5000/nrl/?${queryParams}`,
(err, response, body) => {
if (err) {
console.error(err);
return next(err);
}
res.type(response.headers["content-type"]).send(body);
}
);
// or if you switch to Axios
try {
const { data } = await axios.get("http://127.0.0.1:5000/nrl/", {
params: req.query,
});
res.send(data);
} catch (err) {
console.error(err.toJSON());
next(err);
}
});