Search code examples
node.jsexpressbackend

Request body undefined


I have this post request that is being initiated in the frontend:

const response = await fetch("http://localhost:5000/createUser", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              email: user.email,
            }),
          });

And here in my express/node backend, I am only logging the request body:

app.post('/createUser', async (req, res) => {
  try {
    console.log('Request body:', req.body);
  } catch (error) {
    console.error('Error creating user:', error);
  }
});

However, this is what is logged to the console:

Request body: undefined

I am unsure why this is occurring. I have GET requests that work perfectly fine, and this is the only POST I am doing. Does anyone know how I can fix this?


Solution

  • I'm almost sure that you forgot to use json parser in you server

    app.use(express.json())