user1452030
user1452030

Reputation: 1021

Typescript & Express - Routing not working

I'm following the tutorial here to setup a simple express-typescript application. But for some reason, my routes aren't working as expected. I see quite a few questions on this topic, but nothing that exactly matches my problem. So apologies if this has already been asked and answered.

app.ts

import express from 'express';
import bodyParser from 'body-parser';
import ngrok from 'ngrok'
import IController from './controller.interface'
import SessionController from './sessions/sessions.controller'
 
class App {
  public app: express.Application;
  public port: number;
 
  constructor(controllers: IController[], port: number) {
    this.app = express();
    this.port = port;
 
    this.initializeMiddlewares();
    this.initializeControllers(controllers);
  }
 
  private initializeMiddlewares() {
    this.app.use(bodyParser.json());
  }
 
  private initializeControllers(controllers: IController[]) {
    controllers.forEach((controller) => {
      console.log(controller.path);
      console.log(controller.router);
      this.app.use(controller.path, controller.router);
    });
  }
 
  public listen() {
    this.app.listen(this.port, () => {
      console.log(`App listening on the port ${this.port}`);
      ngrok.connect({proto: 'http', addr: this.port});
    });
  }
}
 
export default App;

controller.interface.ts

import * as express from 'express';
 
interface IController {
  path: string,
  router: express.Router
}
 
export default Controller;

server.ts

import App from './app';
import SessionController from './sessions/sessions.controller';
 
const app = new App(
  [
    new SessionController()
  ],
  3999
);
 
app.listen();

sessions/session.interface.ts

interface Session {
  sessionId: string;
}
 
export default Session;

sessions/sessions.controller.ts

import * as express from 'express';
import Session from './session.interface';
import IController from '../controller.interface'
 
class SessionController implements IController{
  public path = '/sessions';
  public router = express.Router();
 
  private session: Session =
    {
      sessionId: "ABCD12345"
    };
 
  constructor() {
    this.intializeRoutes();
  }
 
  public intializeRoutes() {
    console.log("Route initialised");
    this.router.get(this.path, this.getSession);
  }

  getSession = (request: express.Request, response: express.Response) => {
    console.log("Get session call");
    response.send(this.session);
  }
}
 
export default SessionController;

Output

[nodemon] 2.0.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: ts,json
[nodemon] starting `ts-node src/server.ts`
Route initialised
/sessions
[Function: router] {
  params: {},
  _params: [],
  caseSensitive: undefined,
  mergeParams: undefined,
  strict: undefined,
  stack: [
    Layer {
      handle: [Function: bound dispatch],
      name: 'bound dispatch',
      params: undefined,
      path: undefined,
      keys: [],
      regexp: /^\/sessions\/?$/i,
      route: [Route]
    }
  ]
}
App listening on the port 3999

No other errors, log statements or warnings.

But GET http://localhost:3999/sessions

Does not call the getSession method and I see a Cannot GET /sessions message on screen.

Upvotes: 1

Views: 1761

Answers (1)

Anatoly
Anatoly

Reputation: 22758

It seems you registered the router as /sessions as well as the GET route inside it using the same path prop. So I suspect in this configuration you will get a correct response using

GET http://localhost:3999/sessions/sessions

Indicate / either while registering the whole router or on registering this.router.get

Upvotes: 1

Related Questions