属性"正文"在类型"请求"上不存在



req request> request type boter Intellisense 的变量>。这是由于打字吗?

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)
    }
}

身体偏头被从express 4中删除到单独的项目,因此不会有任何类型的定义。

我这样使用:

import * as bodyParser from 'body-parser';
let router: Router = express.Router();
router.use(bodyParser.text());
(req: Request, res: Response) => {
    let address = req['body'];
}

i仅:

npm install @typings/express --save-dev

,它给了我智能,并允许识别'req.body'。

[解决方案]请求&响应

您只需要以下面的方式导入类型,它将起作用

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

当我做Express.Request

时它不起作用

[附加]解析请求正文

从Express v4.18开始,您不需要单独的软件包,例如body-parser

您可以像以下

那样做
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' }));

请注意,我将两件事放在express.urlencoded&express.json因为我发现该表格数据发布请求不仅可以使用express.json。因此,请保持两种措施,以要求req.body

要求各种JSON有效载荷

我通过添加:

来更改开发依赖项中的 package.json文件来解决它。
"@types/express": "^4.17.17",

相关内容

最新更新