Empty array when sending get request

29 views Asked by At

I am trying to find a user by name, on my backend everything works fine but in React i get empty array, here is the code:

frontend:

  const [name, setName] = useState("");
  const [receiver, setReceiver] = useState([]);

  const findReceiver = (e) => {
    e.preventDefault();
    const body = {name};

    axios.get("http://localhost:3002/user", body)
    .then((foundReceiver) => {
      setReceiver(foundReceiver.data);
    });
  };

backend:

router.get("/user", (req, res, next) => {
  const{name} = req.body
  User.find({firstName: name})
    .then((allUsers) => res.status(200).json(allUsers))
    .catch((error) => next(error));
});

variable name always get the value I type but it looks like it never send it to request.

1

There are 1 answers

0
Sudip Shrestha On

You are trying to send a GET request with a request body. GET request are used to retrieve data from the server, not to send data to the server. You should send the name as a query parameter in the URL rather than in the request body.

FrontEnd

const [name, setName] = useState("");
const [receiver, setReceiver] = useState([]);

const findReceiver = (e) => {
  e.preventDefault();

  axios.get(`http://localhost:3002/user?name=${name}`)
    .then((foundReceiver) => {
      setReceiver(foundReceiver.data);
    })
    .catch((error) => {
      // Handle error
    });
};

Backend

router.get("/user", (req, res, next) => {
  const { name } = req.query;

  User.find({ firstName: name })
    .then((allUsers) => res.status(200).json(allUsers))
    .catch((error) => next(error));
});