Property 'body' does not exist on type 'Request'
Asked Answered
F

5

8

The req variable of Request type has no intellisense for property body. Is this due to the typings?

import { Request, Response } from 'express'
import { ok, bad } from './responses'

export const signIn: async (req: Request, res: Response) => {
    try {
        const { name, pword } = req.body // body is not recognized
        const data = auth.signIn(name, password)
        ok(res, data)
    } catch (error) {
        bad(res, error)
    }
}
Fowl answered 2/6, 2017 at 9:26 Comment(0)
S
1

body-parser had been removed from express 4 into separate project, so there won't be any type definition about it.

I use it this way:

import * as bodyParser from 'body-parser';

let router: Router = express.Router();
router.use(bodyParser.text());

(req: Request, res: Response) => {
    let address = req['body'];
}
Sublittoral answered 2/6, 2017 at 9:38 Comment(3)
i think bodyParser.json() - is more common use case.Gabo
yeah, I forgot, req['body'] is same as req.body. but the form req.body is much more js oriented.Fowl
body-parser is most certainly still included as a dependency of express ~ github.com/expressjs/express/blob/4.18.2/package.json#L33Steric
F
1

i just:

npm install @typings/express --save-dev

and it gave me the intellisense and allow to recognize 'req.body'.

Fowl answered 2/6, 2017 at 12:24 Comment(1)
Thanks! Knew I was missing something! ;) alternatively yarn add @types/expressOrji
V
1

[Solution] Type For Request & Response

You just have to import types like below and it will work

import { Request, Response } from 'express';

...

app.post('/signup', async (req: Request, res: Response) => {
        const { fullName, email } = req.body;
        ...
    })
);

It didn't work when I did Express.Request

[Additional] Parsing Request Body

As of express v4.18, you don't need separate package like body-parser

You can do like below

import express from 'express';


const app = express();

// Parse request body
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// Test Route
app.get('/', (req, res) => res.json({ message: 'Hello World' }));


Notice that I have put two things above express.urlencoded & express.json because I found that form data post request was not working with just express.json. So keeping both of them parses all kinds of json payload in request to req.body

Vigen answered 10/6, 2023 at 4:54 Comment(0)
C
0

For Node v.20.x this still working

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

but VERY important order, middlewares should be BEFORE routes, not after.

Comical answered 28/2, 2024 at 4:45 Comment(0)
E
-2

I managed to solve it by changing the package.json file in development dependencies by adding:

"@types/express": "^4.17.17",
E answered 17/7, 2023 at 0:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.