How to throw 404 error in express.js?

In app.js I have

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

so if I ask that some of them do not look like url like http://localhost/notfound , the code will be executed.

In an existing url, like http://localhost/posts/:postId , I would like to reset the 404 error when access does not exist postId or removed postId.

 Posts.findOne({_id: req.params.id, deleted: false}).exec() .then(function(post) { if(!post) { // How to throw a 404 error, so code can jump to above 404 catch? } 
+5
source share
4 answers

In Express, 404 is not classified as an β€œerror”, so to speak - the argument is that 404 isn This is usually a sign that something went wrong, just the server did not find anything. It is best to explicitly send 404 to the route handler:

 Posts.findOne({_id: req.params.id, deleted: false}).exec() .then(function(post) { if(!post) { res.status(404).send("Not found."); } 

Or, conversely, if it seems like too much repeating code, you can always output that code to a function:

 function notFound(res) { res.status(404).send("Not found."); } Posts.findOne({_id: req.params.id, deleted: false}).exec() .then(function(post) { if(!post) { notFound(res); } 

I would not recommend using middleware in this situation just because I feel that it makes the code less clear - 404 is a direct result of the database code that does not find anything, so it makes sense to have a response in the route handler.

+3
source

I have the same app.js structure, and I solved this problem this way in the route handler:

 router.get('/something/:postId', function(req, res, next){ // ... if (!post){ next(); return; } res.send('Post exists!'); // display post somehow }); 

The next() function will call the next middleware, which is the error404 handler if it is right after your routes in app.js.

+2
source
0
source

You can use this and the end of your routers.

 app.use('/', my_router); .... app.use('/', my_router); app.use(function(req, res, next) { res.status(404).render('error/404.html'); }); 
0
source

Source: https://habr.com/ru/post/1247854/


All Articles