使用body-parser解析中间件的顺序

时间:2019-05-06 20:51:38

标签: node.js typescript express body-parser

好的,所以我试图理解Node.js和Typescript,所以我尝试使用如下的简单脚本;

  1. 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;
  1. ./ 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"}));
    }
}
  1. 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很陌生,指针会很棒。

1 个答案:

答案 0 :(得分:2)

应在实际路由之前调用主体解析器(或一般的中间件)。

您的路线不起作用,因为您在这里遇到拼写错误:

this.app.use(bodyParser.json);

应该是:

this.app.use(bodyParser.json());

当您将代码放在最后时,该路由才起作用,因为它从未真正执行过(该路由首先被匹配并停止执行,因为您没有调用next()函数)

相关问题