[英]express.Router hitting 404 instead of route when separated in own files
I am having trouble understanding weird express.Router() behaviour.我无法理解奇怪的 express.Router() 行为。 I decided to tidy up my routes to enable better API versioning.
我决定整理我的路线以启用更好的 API 版本控制。 If I keep simpler structure like below, everything works as expected :
如果我保持像下面这样更简单的结构,一切都会按预期进行:
app.js应用程序.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) v1.js(api 版本/api 索引文件)
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:但是如果我将这些路由移动到一个单独的文件中,请导出 Router 并将其导入如下:
ordersRoutes.js订单路由.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 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!我在每个订单路线上都遇到了 404,这很奇怪,因为与其他文件相同的方法工作得很好(我将它们比较了很多次...... :( )。我的假设是它与路由器的太多实例有关,或者可能路线的排序,但我不能指望它。任何想法都非常感谢。提前致谢!
In your app.js, next(err) function forcing other routes to response an 404 error.在您的 app.js 中,next(err) 函数强制其他路由响应 404 错误。 You should remove err argument from function.
您应该从函数中删除 err 参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.