Search code examples
node.jstypescriptexpressbackendbody-parser

Express + Typescript: Property 'body' does not exist on type 'Request'


I got the following code:

import bodyParser from 'body-parser';
import express, { Router } from 'express';

const router: Router = express.Router();

router.use(bodyParser.json());

router.post('/api/users/signup', (req: express.Request, res: express.Response) => {
    const {email, password} = req.body;

    if (!email || typeof email !== 'string') {
        res.status(400).send('Provide a valid email');
    }
});

export {router as signUpRouter};

Here, the req.body is showing the error of

Property 'body' does not exist on type 'Request'

And I have downloaded following libraries:

npm install express @types/express body-parser @types/body-parser typescript ts-node-dev

Solution

  • If you're using the new node version( v14+) and Express v4.16.0 onwards, replace

    router.use(bodyParser.json());

    with

    router.use(express.json());