0

I use Express with Typescript and Controllers. I try to make a BaseController who contains Request and Response of each request. I tried something like this but it doesn't work.

export * as express from 'express';

const req = express.Request;
Flimzy
  • 60,850
  • 13
  • 104
  • 147
bonblow
  • 801
  • 4
  • 13
  • 25
  • 1
    The request and response are passed in the controller methods that handle them. They are not global objects https://stackoverflow.com/questions/4696283/what-are-res-and-req-parameters-in-express-functions – Ivan Mladenov Nov 21 '18 at 09:08

1 Answers1

0

You can create "Controller" classes to group your route handlers, but Express always pass req and res (Request and Response objects) to the route handlers.

Exemple using TypeScript:

// very simplistic example

// "Controller" class
export class UsersController {
  // route handler
  async getUsers(req: Request, res: Response) {
    try {
      const users = await this.usersRepository.fetchUsers();
      return res.json(users);
    } catch (e) {
      console.error(e);
      return res.status(500).end();
    }
  }
}

And somewhere with your Express router:

const usersController = new UsersController();
app.get('/users', usersController.getUsers);

As a bonus suggestion, I'd recommend having a look at the Nest project, which offers a great developer experience to anyone eager to use both TypeScript and Express together.

VinceOPS
  • 1,990
  • 13
  • 15