如何修改Express路由,在blogs/:blogId错误ID时渲染404页面
Got it, let's sort out this issue where entering an invalid or non-existent blog ID in /blogs/:blogid doesn't trigger your 404 page. Here's the step-by-step fix for your code:
Problem with Your Current Code
Right now, your route only handles database query errors (like a completely malformed ObjectId), but it doesn't account for valid-looking IDs that don't match any blog post in your database. In that case, addedblogpost will be null, and your code will still try to access properties like addedblogpost.blogTitle—which will throw an error instead of showing the 404 page.
Modified Blog Detail Route
Update your /blogs/:blogid route to check both for errors AND missing blog posts:
app.get('/blogs/:blogid', (req, res) => { const requestedId = req.params.blogid; Blog.findById(requestedId, (err, addedblogpost) => { // Handle database errors (e.g., invalid ObjectId format) if (err) { console.log(err); return res.render('404'); } // Handle case where no blog post matches the ID if (!addedblogpost) { return res.render('404'); } // If everything checks out, render the post page res.render("post", { title: addedblogpost.blogTitle, content: addedblogpost.blogContent }); }) })
Key Changes Explained
- Split error handling: We first catch database-level errors (like invalid ID formats) and immediately render the 404 page.
- Check for missing posts: When
addedblogpostisnull(meaning the ID is valid but no post exists), we also render the 404 page. - Use
return: This ensures that after rendering 404, we don't execute the code that tries to render the post page—preventing unexpected errors.
Quick Note About Your 404 Route
Make sure your wildcard 404 route (app.get('*', ...)) stays at the very end of all your route definitions. This ensures it only triggers when no other routes match the request, which is exactly what we want.
内容的提问来源于stack exchange,提问作者coderharsh19

