0

I'm new to NodeJs and express. My goal is to have a separate route file that contains all my application routes. So I created a file called routes.js. The content looks like this:

const express = require('express');

const router = express.Router();

router.get('auth/register', require('./controllers/auth/register'));

module.exports = router;

In my main file, I require the file with this line. The app variable contains my express instance.

app.use('/', require('./routes'));

If I call http://localhost/auth/register in my browser, I'm always running into a 404 Not Found error. When I define the route directly in the main file with app.get('/auth/register', require('./controllers/auth/register')); it works well. There are no errors in my console.

Has anyone an idea why my sperate route file does not work? Thank you for your help!

Markus
  • 1,909
  • 4
  • 26
  • 54

2 Answers2

1

You want to pass app into your routes file. A good pattern for this is to import your routes in your main file, like const routes = require('./routes');

In routes, you can define all of your routes like so:

module.exports = (app, router) => {
  router.route("/").get()
  router.route("/something_else").post()
  app.use("/api", router)
  ...
};

This way, in your main file, you can do: routes(app, router) and have access to app and router inside your routes.js.

c_sagan
  • 482
  • 3
  • 15
1

Traditionally, I do the following which is to pass the express instance into your routes module:

once I have instantiated my express instance called app

app.js

require('./routes.js')(app);

routes.js where registerUser us the function to call when the route is matched

module.exports = (app) => {
   app.route('/auth/register')
    .post(registerUser);
}
Samuel Goldenbaum
  • 18,391
  • 17
  • 66
  • 104
  • can you share more of the main code where you instantiate express and then register the routes. If you still doing: app.use('/', require('./routes')); then it will not work. – Samuel Goldenbaum Nov 12 '19 at 21:35
  • Sorry, my mistake. I didn't realize that you use post instead of get. The solution works fine for me. – Markus Nov 12 '19 at 21:36
  • 2
    Great, I suggest creating separate route files for your various endpoints so you don't have a ton of routes to wade through in a single file. – Samuel Goldenbaum Nov 12 '19 at 21:39