Cannot destructure Property `name` of 'Undefined' or 'null'

Asked

Viewed 1,903 times

0

for some reason my req.body is returning Undefined, even with the correct middleware.

Controller

import { Request, Response } from 'express';
import db from '../database/connection';

class ClassesController {
  public async store(req: Request, res: Response): Promise<Response> {
    try {
      const { name, avatar, whatsapp, bio } = req.body;

      await db('users').insert({
        name,
        avatar,
        whatsapp,
        bio,
      });

      return res.json({ msg: 'Sent' });
    } catch (err) {
      return res.status(400).json({ error: err.message });
    }
  }
}

export default new ClassesController();

Classesroutes

import { Router } from 'express';
import ClassesController from '../controller/ClassesController';

const routes = Router();

routes.post('/classes', ClassesController.store);

export default routes;

App

import 'dotenv/config';
import express from 'express';

import ClassesRoutes from './routes/ClassesRoutes';

class App {
  app: express.Application;

  constructor() {
    this.app = express();

    this.routes();
    this.middlewares();
  }

  middlewares() {
    this.app.use(express.json());
    this.app.use(express.urlencoded({ extended: false }));
  }

  routes() {
    this.app.use(ClassesRoutes);
  }
}

export default new App().app;

Server

import App from './app';

const port = process.env.APP_PORT;
App.listen(port, () => console.log(`Conectado em http://localhost:${port}`));

Error in itself inserir a descrição da imagem aqui

Does anyone know why this is happening?

1 answer

1


Do not use classes if you do not need them, they are complex objects and should not be used uselessly, everything you wrote in for your App could be reduced by:

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(ClassesRoutes);

The same goes for your ClassesController, you could simply export an object with inside the methods you need, anyway possible cause for your problem:

this.routes();
this.middlewares();

After you created your app, you first set the routes and only then the middlewares, your application will mount the stack of "handlers" in order of call, ie you set Handler to the request even before you have done the parsing body of the same, which means that it does not exist to your controller, simply reversing should solve your problem:

this.middlewares();
this.routes(); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.