Tuesday 23 May 2017

Express Middleware: Pass res.locals to an instance of a router

I'm trying to access res.locals that is set in custom middleware in a custom express router for a path. However, it looks like res.locals is not being passed to my instance of the router.

Here's the relevant code (It's in typescript):

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;

Here is where I've defined the express app:

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;

Is there some behavior that I'm unaware of that prevents res.locals from getting passed to the MyRouter instance?



via RohanC

No comments:

Post a Comment