nodejs – req.body returns undefined when sent to be handled in anther file

I’m working on a project involving nodejs and I’m having a problem with a request body that is undefined

On the client side I fetch some data

const userData = {
    username,
    email,
    password
};

fetch(API_URL, {
    method: 'POST',
    body: JSON.stringify(userData),
    headers: {
        'content-type': 'application/json'
    }
});

Then I have a file on the serverside called index.js

const express = require('express');
const cors = require('cors');
const { signup, login } = require ('./authController');

app.post('/signup', (req, res) =>{
    console.log(req.body);

    signup(req.body)
}); 

When I log req.body in "app.post" The values are correct but when i log it in this next file called authController.js it is suddenly undefined

const { createUser, findUserByEmail } = require('./user');
const { comparePassword, createToken } = require('./auth');

// Controller function to handle a signup request
async function signup(req, res) {
    console.log(req.body);
  try {
   
  } catch (error) {
    
  }
}

I also get the following error telling me the property is undefined or null

TypeError: Cannot destructure property email of ‘undefined’ or ‘null’.

Anyone know what might cause this and how I can fix this, all help is greatly appreciated.

>Solution :

Convert body: JSON.stringify(userData), to body: userData
Add app.use(express.json() above app.post so you can work with the json. req.body should have an email property on the server when fetching now. Your function signup takes 2 arguments, (req, res) instead of (req.body) BTW.

const userData = {
    username,
    email,
    password
};

fetch(API_URL, {
    method: 'POST',
    body: userData,
    headers: {
        'content-type': 'application/json'
    }
});
const express = require('express');
const cors = require('cors');
const { signup, login } = require ('./authController');

app.use(express.json())

app.post('/signup', signup)
const { createUser, findUserByEmail } = require('./user');
const { comparePassword, createToken } = require('./auth');

// Controller function to handle a signup request
async function signup(req, res) {
    console.log(req.body);
  try {
   
  } catch (error) {
    
  }
}

Leave a Reply