0

I am trying to attach an object to the GET request to the Node backend, however when I console log the req.body from my backend, it shows that the req.body came in empty. This is my React code:

 useEffect(() => {
    const fetchMessages = async () => {
      const { data } = await axios.get('/api/messages', {
        sender: '5ffadc2710d93b21a812c33b',
        receiver: '5ffadc1510d93b21a812c339',
      });
      setMessages(data.messages);
      console.log(data);
    };
    fetchMessages();
  }, []);

I am attaching the object with the keys sender and receiver to the backend to fetch messages between the sender and receiver. This is my backend code, where on line 4 I am console logging the req.body, which returns an empty object.

Router.route('/').get(
  asyncHandler(async (req, res) => {
    const { sender, receiver } = req.body;
    console.log(req.body);
    const user = await User.findOne({ _id: sender });
    const user2 = await User.findOne({ _id: receiver });
    let sentMessages = await Message.find({ sender, receiver });
    let receivedMessages = await Message.find({
      sender: receiver,
      receiver: sender,
    });
    let messages = sentMessages.concat(receivedMessages);
    messages.sort((a, b) => a.time.getTime() - b.time.getTime());
    res.status(200).json({
      sender: user,
      receiver: user2,
      messages,
    });
  })
);
Aidenhsy
  • 915
  • 2
  • 13
  • 28

2 Answers2

1

Axios library is opiniated, it doesn't let you add a body to a GET request. Use axios.post for that.

Quentin C
  • 1,739
  • 14
  • 26
  • 1
    Thanks I just changed it to post and it works,, I also just read this https://stackoverflow.com/questions/40947650/axios-get-in-url-works-but-with-second-parameter-as-object-it-doesnt – Aidenhsy Jan 13 '21 at 01:14
0

What about json parser in your app middlewares?

[...] //express/node setup

app.use(express.json())

[...]//rest of configuration
Gabe Leon
  • 25
  • 1
  • 6
  • I have my json parser set up, when I try to send the request with Postman, it works, so there's a problem with my frontend React files – Aidenhsy Jan 13 '21 at 00:52
  • Oh I see. So you sending files with FormData? If you're not, try using it. [FormData info](https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData) – Gabe Leon Jan 13 '21 at 16:42