Ант*_*сун 3 javascript node.js express typescript body-parser
这是我使用 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);
});
}
}`
Run Code Online (Sandbox Code Playgroud)
请帮我解决这部分代码。我不明白,当我发送帖子请求时,为什么我在 request.body 中未定义。
小智 5
如果您运行的是express 4.16或更高版本,则不再需要使用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(express.json());
this.app.use(express.urlencoded());
this.app.use("/", controller.router);
});
}
}`
Run Code Online (Sandbox Code Playgroud)
请参阅此处了解更多信息:https://medium.com/@mmajdanski/express-body-parser-and-why-may-not-need-it-335803cd048c
归档时间: |
|
查看次数: |
11667 次 |
最近记录: |