使用 body-parser 解析中间件的顺序
Order of middleware parsing with body-parser
好的,所以我正在尝试理解 Node.js 和 Typescript,所以我尝试编写一个简单的脚本,如下所示;
- app.ts
import * as express from "express";
import * as bodyParser from "body-parser";
import { Routes } from "./routes/crm_routes";
class App {
public app;
public routePrv : Routes = new Routes();
constructor() {
this.app = express();
this.routePrv.routes(this.app);
this.config();
}
private config():void {
this.app.use(bodyParser.json);
this.app.use(bodyParser.urlencoded({ extended: false }));
}
}
export default new App().app;
- ./lib/routes/crm_routes.ts
import {Request, Response} from "express";
export class Routes {
public routes(app): void {
app.route('/').get((req, res) => res.json({name : "ohmygodnotthisagain"}));
}
}
- server.ts
import app from "./app";
app.listen(3000, () => console.log('Example app listening on port 3000!'));
现在我在玩弄所以我把 this.config() 放在 this.routePrv.routes(this.app) 上面,我的服务器完全停止路由到 /。
当我按上面的顺序放回它们时,它又开始工作了。
现在我试图了解造成这种情况的原因,但很困惑,是因为 body-parser 需要成为最后一个调用的中间件,这样 auth、额外检查等中间件才能完成工作,还是还有其他原因?
我们将不胜感激任何帮助。谢谢!
PS: 我是 TS 的新手,指点会很棒。
主体解析器(或一般的中间件)应在实际路由之前调用。
你的路线不工作,因为你在这里有一个拼写错误:
this.app.use(bodyParser.json);
应该是:
this.app.use(bodyParser.json());
当您将该代码放在最后时,该路由有效,因为它从未真正执行过(路由首先匹配并停止执行,因为您没有调用 next()
函数)
好的,所以我正在尝试理解 Node.js 和 Typescript,所以我尝试编写一个简单的脚本,如下所示;
- app.ts
import * as express from "express";
import * as bodyParser from "body-parser";
import { Routes } from "./routes/crm_routes";
class App {
public app;
public routePrv : Routes = new Routes();
constructor() {
this.app = express();
this.routePrv.routes(this.app);
this.config();
}
private config():void {
this.app.use(bodyParser.json);
this.app.use(bodyParser.urlencoded({ extended: false }));
}
}
export default new App().app;
- ./lib/routes/crm_routes.ts
import {Request, Response} from "express";
export class Routes {
public routes(app): void {
app.route('/').get((req, res) => res.json({name : "ohmygodnotthisagain"}));
}
}
- server.ts
import app from "./app";
app.listen(3000, () => console.log('Example app listening on port 3000!'));
现在我在玩弄所以我把 this.config() 放在 this.routePrv.routes(this.app) 上面,我的服务器完全停止路由到 /。 当我按上面的顺序放回它们时,它又开始工作了。
现在我试图了解造成这种情况的原因,但很困惑,是因为 body-parser 需要成为最后一个调用的中间件,这样 auth、额外检查等中间件才能完成工作,还是还有其他原因?
我们将不胜感激任何帮助。谢谢! PS: 我是 TS 的新手,指点会很棒。
主体解析器(或一般的中间件)应在实际路由之前调用。
你的路线不工作,因为你在这里有一个拼写错误:
this.app.use(bodyParser.json);
应该是:
this.app.use(bodyParser.json());
当您将该代码放在最后时,该路由有效,因为它从未真正执行过(路由首先匹配并停止执行,因为您没有调用 next()
函数)