0

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

4
  • 1
    request is deprecated and has been for some time. I would recommend Axios or got Commented Jul 22, 2022 at 5:40
  • 1
    Are you sure that URL is correct? Usually URL query parameters start with a ? Commented Jul 22, 2022 at 5:43
  • Axios works in the backend side of this too? I'll change it. Ill double check the URL Commented Jul 22, 2022 at 6:29
  • 1
    Yep, Axios works in browsers and NodeJS Commented Jul 22, 2022 at 6:30

1 Answer 1

1

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);
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

How does my frontend request know to use that particular backend controller? I don't understand how its called.
@Bigred I assumed you already had an app route handling /nrl. I've updated my answer to be a bit more specific

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.