英文:
How to handle unknown routes in Express
问题
app.js
app.use('/', userRoutes);
app.use('/adminID', adminRoutes);
app.all('*', (req, res, next) => {
next(new AppError(`Url Not Found ${req.originalUrl}`, 404));
}) const ErrorHandler = require('./ErrorHandler.js');
app.use(ErrorHandler);
module.exports = app;
英文:
I am at a complete lost
app.js
app.use('/', userRoutes);
app.use('/adminID', adminRoutes);
app.all('*', (req, res, next) => {
next(new AppError(`Url Not Found ${req.originalUrl}`, 404));
}) const ErrorHandler = require('./ErrorHandler.js');
app.use(ErrorHandler);
module.exports = app;
答案1
得分: 0
我不确定为什么它有效。但在发出请求的函数中删除next()
可以解决我的问题。
我刚刚今天阅读到,不必手动调用next()
。如果有错误,它将被默认调用。
exports.create = CatchAsync(async (req, res, next) => {
console.log(req.originalUrl)
const content = await ContentModel(req.body)
res.send(content)
await content.save()
// 请注意我没有调用next()
// 在express 5之前,我认为您必须调用next(),以便运行下一个中间件。但现在不是这种情况。
})
愉快的编码!
英文:
I am not sure why it works. But removing next()
in the function that makes the request. Solves the problem for me.
I was just reading today that, the next()
doesn't have to be called. Manually, if there is an error it will get called by default.
exports.create = CatchAsync(async (req, res, next) => {
console.log(req.originalUrl)
const content = await ContentModel(req.body)
res.send(content)
await content.save()
// notice how I'm not calling next()
// before express 5, I believe you had to call next() so the next middleware would run. That is not the case now.
})
Happy Coding!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论