Reputation: 8828
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)
}
}
Upvotes: 8
Views: 14619
Reputation: 5
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.
Upvotes: 0
Reputation: 1
I managed to solve it by changing the package.json
file in development dependencies by adding:
"@types/express": "^4.17.17",
Upvotes: -2
Reputation: 8828
i just:
npm install @typings/express --save-dev
and it gave me the intellisense and allow to recognize 'req.body'.
Upvotes: 1
Reputation: 2119
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
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
Upvotes: 1
Reputation: 22797
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'];
}
Upvotes: 1