Home > Back-end >  How to handle unknown routes in Express
How to handle unknown routes in Express

Time:01-10

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;

question as an image

CodePudding user response:

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!

  • Related