skip to Main Content

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

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.

2

Answers


  1. here ‘s fixing

    const userData = {
    username:'deathstar',
    email:'[email protected]',
    password:'ssss'
    

    };

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

    });

    this is back-end code too

     const express = require('express');
      const cors = require('cors');
      
      const fs = require('fs');
       const path = require('path');
       const app = express();
    
       const port = 5500;
    
       app.use(cors()); // enable CORS
    
      app.use(express.json());
      app.use(express.urlencoded({ extended: true }));
    
       app.use(express.static(__dirname + '/public'));
    
       app.get('/',(req,res)=>{
    
     res.sendFile('index.html');
      });
    
      app.post('/signup', (req, res) =>{
       console.log(req.body);
    
          }); 
    
         app.listen(port, () => console.log(`Example app listening on port ${port}!`)); 
    
    Login or Signup to reply.
  2. 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) {
        
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search