简体   繁体   中英

express.Router hitting 404 instead of route when separated in own files

I am having trouble understanding weird express.Router() behaviour. I decided to tidy up my routes to enable better API versioning. If I keep simpler structure like below, everything works as expected :

app.js

app.use('/v1', v1);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

v1.js (api version / api index file)

module.exports = router;
router.post('/orders',    auth.isUser, OrderController.create);
router.get('/orders',     auth.isUser, OrderController.getAll);
router.get('/orders/:id', auth.isUser, OrderController.get);
router.put('/orders/:id', auth.isEmployee, OrderController.update);

but if I move these routes to a separate file, export Router and import it as below:

ordersRoutes.js

const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const OrderController = require('../controllers/OrderController');

module.exports = router;

// routes for endpoint
// hostname/v1/orders/*
router.post(    '/orders',        auth.isUser, OrderController.create);
router.get(     '/orders',        auth.isUser, OrderController.getAll);
router.get(     '/orders/:id',    auth.isUser, OrderController.get);
router.put(     '/orders/:id',    auth.isEmployee, OrderController.update);

v1.js

const router              = express.Router();
const ordersRoutes = require('./ordersRoutes');

module.exports = router;

router.use( '/orders',     ordersRoutes         );

I hit 404 on every order route, which is weird because the same approach with other file works just fine (I compared them many times... :( ). My assumption is that it has to do with too many instances of Router or maybe ordering of routes, but I cant put my finger on it. Any ideas are much appreciated. Thanks in advance!

In your app.js, next(err) function forcing other routes to response an 404 error. You should remove err argument from function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM