2

I have created registerClass where i will add all the routes for this application , this node app is using typescript so all the source is in dist directory. what i am missing in below code when i call http://localhost:9001/user endpoint it is not going into registerRouteClass ? i guess it is not reading the dist dir

server.js

const express = require("express"),
    path = require("path"),
    app = express();
var router = require('./dist');

app.use(express.static(path.join(__dirname, 'dist')));
app.use(new router.TRouter().getRouter);

app.listen(9001, () => console.log('Example app listening on port 9001!'));

routes.ts

import {UserController} from './api/user/user.controller';
export class RegisterRouteClass {
    public RegisterRoutes(app: any) {
      console.log("registing routes");
        app.post('/user', UserController.findAll);
    }

}

index.ts

import {NextFunction, Request, Response, Router} from 'express';
import * as bodyParser from 'body-parser';
import {RegisterRouteClass} from "./routes";

// this variable will be exported to be included as a middleware.
class TRouter extends RegisterRouteClass {
    private TRouter: any;

    constructor() {
        super();
        this.TRouter = Router();
        this.TRouter.use(bodyParser.json());
        this.TRouter.use(bodyParser.urlencoded({extended: false}));
        this.TRouter.use(function(_req: Request, res: Response, next: NextFunction) {
            // CORS header
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
            res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
            res.setHeader("Content-Type", "application/json");
            next();
        });

    }

    public get getRouter() {
        return this.TRouter;
    }


}


export {TRouter};

directory structure

Project
 - dist 
  -index.js
  -routes.js
  -api
   - user
     -user.constrollr.js
-server.js
hussain
  • 6,587
  • 18
  • 79
  • 152

1 Answers1

0

First of all your project structure looks little bit odd but, in your server.js, by var router = require('./dist') you are not actually requiring anything since in your index.js you don't have a default export only name export.

You should either have a default export in your index.ts or do var router = require('./dist').TRouter. I'd go with default export.

Samin
  • 1