正文解析器不适用于打字稿,当我发送请求时,我在request.body中得到一个未定义的



以下是我使用typescript 3.7.4的express应用程序的代码:

import bodyParser from "body-parser";
import config from "config";
import cookieParser from "cookie-parser";
import express from "express";
import mongoose from "mongoose";
import path from "path";
export default class App {
public app: express.Application;
constructor() {
this.app = express();
this.initializeMiddlewares();
}
public listen(port: any) {
this.app.listen(port, () => {
console.log(`App listening on the port ${port}`);
});
}
public initializeControllers(controllers: any) {
controllers.forEach((controller: any) => {
this.app
.use(bodyParser.json())
.use(bodyParser.urlencoded())
.use("/", controller.router);
});
}
}`

请帮我处理这部分代码。我不明白,为什么我在请求中没有定义。正文,当我发送邮件请求时。

如果您正在运行express 4.16或更高版本,则不再需要使用body解析器。

你可以试着这样做:

import config from "config";
import cookieParser from "cookie-parser";
import express from "express";
import mongoose from "mongoose";
import path from "path";
export default class App {

public app: express.Application;
constructor() {
this.app = express();
this.initializeMiddlewares();
}
public listen(port: any) {
this.app.listen(port, () => {
console.log(`App listening on the port ${port}`);
});
}
public initializeControllers(controllers: any) {
controllers.forEach((controller: any) => {
this.app.use(express.json());
this.app.use(express.urlencoded());
this.app.use("/", controller.router);
});
}
}`

请参阅此处了解更多信息:https://medium.com/@mmajdanski/express-body-parser-and-why-may-not-need-it-335803cd048c

相关内容

最新更新