Express Middleware:将res.locals传递给路由器的实例

时间:2017-05-24 04:01:02

标签: node.js express middleware

我正在尝试访问自定义快速路由器中的自定义中间件中为路径设置的res.locals。但是,看起来res.locals没有传递给我的路由器实例。

这是相关的代码(它在打字稿中):

MyRouter.ts:

import { Router, Request, Response, NextFunction } from 'express';

export class MyRouter {
  router: Router;

  constructor() {
    this.router = Router();
    this.init();
  }

  // Handle Get
  public getHandler(req: Request, res: Response, next: NextFunction) {
      // res.locals is UNDEFINED here
      Service.getData(req.query, res.locals)
      .then(function (result) {
        res.send(result);
      })
      .catch(function (error) {
        res.status(500).send(error.message)
      });
  }

  /**
   * Attach handlers
   */
  init() {
    this.router.get('/', this.getHandler);
  }

}

const myRoutes = new MyRouter();
myRoutes.init();

export default myRoutes.router;

以下是我定义快递应用的地方:

import * as express from 'express';
import MyRouter from './routes/MyRouter';
import { Middleware1,Middleware2 } from './utils/MyMiddleware';

class App {

  public express: express.Application;

  constructor() {
    this.express = express();
    // this sets res.locals
    this.express.use(Middleware1);
    // this next piece of middleware is able to access res.locals
    this.express.use(Middleware2);
    // res.locals is undefined in MyRouter
    this.express.use('/api', MyRouter);
    let router = express.Router();
    router.get('*', (req, res, next) => {
      res.sendFile(path.resolve(__dirname, '..', '..', 'src', 'static', 'index.html'));
    });
    this.express.use('/', router);
  }
}

export default new App().express;

是否有一些我不知道的行为会阻止res.locals传递给MyRouter实例?

0 个答案:

没有答案