HKS
HKS

Reputation: 167

Routing in express

I have structure like this:

server.ts
routes/
    index.ts
    homeRoute.ts

In server.ts:

let app = Express();
app.use(router);

In routes/index.ts:

const routes = Router();
export default function router() {
  routes.use('/home', homeRoute);
}

In routes/homeRoutes.ts

let homeRouter = Express.Router();

export default function homeRoute(req: Request, res: Response, next: NextFunction) {
  console.log('home route');
  homeRouter.get('/home', function);
  next();
}

My problem is when i call http://localhost:3000, it run to index.ts file ( I console.log some things so I know that), however it don't execute my routes.use('/home', homeRoute).
I don't know why it is. Please help me fix it.

Upvotes: 0

Views: 105

Answers (1)

Muthukumar
Muthukumar

Reputation: 9579

Understand how import and export works. Ideally your code should be something like this.

server.ts

import * as express from 'express';
import {routes} from './routes';
const app = express();
routes(app);

routes/index.ts

import {homeRoute} from './homeRoutes';
export const routes = (app) => {
  homeRoute(app);
}

routes/homeRoutes.ts

export const homeRoute = (app) => {
  app.get('/home', function (req, res, next) {
    res.render('home');
  });
}

Upvotes: 1

Related Questions