0

I am currently using Redux and I want to send the state and request it in the backend. Code below.

const { email } = useSelector((state) => state.user);

  const getConcern = async () => {
    const { data } = await axios
      .get("http://localhost:5000/Student/", { email })
      .catch((err) => console.log(err.message));
    console.log(email);
    console.log(data);
  };

And I am trying to log it in the console in the backend but it results as undefined?

const getConcerns = async (req, res) => {
  const { email } = req.body;
  console.log(email);

  const concerns = await Concerns.find();

  res.status(200).json(concerns);
};

How can I send the email in the current state and pass it into the backend as a GET method? Please help, thanks.

XypriL
  • 129
  • 1
  • 1
  • 9
  • Use `req.query` instead of `req.body` on the server, because you send data in the query string, not in the request body. – alexmac Aug 19 '21 at 16:50

3 Answers3

1

get request doesn't have body you can use

await axios.get("http://localhost:5000/Student/", {
  params:{email}
})

and use req.query

Omar Khaled
  • 439
  • 1
  • 4
  • 16
0

I think there are two issues here:

  1. Axios expects a data property in the options object, so your get method call should look like:
await axios.get("http://localhost:5000/Student/", { data: { email } })
  1. While the Http Spec does not explicitly disallow sending a message body with a GET request, both the XHR and fetch APIs used by modern browsers ignore the message body when sending a GET request. Since Axios uses XHR in the browser, the data will be ignored. You can refactor your server route to a POST request if you need to receive data from the client in the request body. You could also use a dynamic route parameter or a query parameter.
Jon Webb
  • 21
  • 2
  • 3
-1

When you use GET, the request does not contain "body".

So, you have to use something like this:

req.query

Check How to get GET (query string) variables in Express.js on Node.js?