如何在Express中处理未知路由

huangapple go评论65阅读模式
英文:

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;

如何在Express中处理未知路由

答案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!

huangapple
  • 本文由 发表于 2023年1月9日 15:00:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定