1

I'm trying to load ExpressJS routes from a Typescript class. The idea is that this should eventually be dynamic routes. But I'm already stuck at defininghard coded routes in a class.

My index.ts js looks like this:

import generic = require('./generic');
import Generic = generic.Generic;

class Test {

  private app:any;
  private port:number = 3000;

  constructor() {
    this.app = express();
    new Generic();
    this.app.listen(this.port, () => {
      console.log('Listening on port ' + this.port);
    });
  }
}

export = Test;
new Test();

Then my generic.ts looks like this. I'm trying to define another route from this class:

module Generic {
  export class Generic {

    constructor() {
      console.log('In generic');

      var router:any = express.Router();

      router.get('/', function (req, res) {
        res.setHeader('Content-Type', 'application/json');
        res.status(200).send("AAA");
      });
    }
  }
}
export = Generic;

When I run my application then I see the message In generic appear in console. But when I load my browser it says:

Cannot GET /

So for some reason it's not really registering the route from the Generic class. What am I doing wrong?

1 Answer 1

2

Take a look at the sample on Microsoft's github page. Rather than using express.Router, they simply use get and import the function from an external module. It has worked pretty well for me.

app.ts

import * as express from "express";
import * as routes from "./routes/index";

var app = express();

app.get('/', routes.index);

routes/index.ts

import express = require("express")

export function index(req: express.Request, res: express.Response) {
    res.render('index', { title: 'ImageBoard'});
};
Sign up to request clarification or add additional context in comments.

2 Comments

This does not answer the question, they are asking about classes
agreed, I am also looking for a class-based approach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.