Node.js中未定义路由时跳转至404页面的实现方案
How to Redirect Undefined Routes to 404 Page in Your Node.js/Express App
Got it, let's get that 404 redirect working for your app! The key thing to remember with Express routing is that routes are matched in the order you define them, so we just need to add a catch-all route at the very end of your router (or app) to handle any undefined paths like /homy.
Step 1: Add a Catch-All Route to Your Router
In your index.js file, add this route after all your existing routes (right before module.exports = router;):
// Catch all undefined routes in this router and redirect to 404 router.get('*', (req, res) => { // Option 1: Render a custom 404 view (recommended for better UX) res.status(404).render('404', { page_title: "Oops! Page Not Found", user: req.session.passport?.user ? JSON.parse(req.session.passport.user) : null }); // Option 2: If you don't have a custom 404 view, send a plain text response // res.status(404).send('404 - Page Not Found'); }); module.exports = router;
Step 2: Ensure the Router is Loaded Last in Your Main App
If you're mounting this router in your main app.js file, make sure you do it after all other routes and middleware. For example:
// Load other routes first app.use('/api', require('./routes/api')); app.use('/', require('./routes/index')); // Your router here // Global catch-all for any remaining undefined routes (optional but safe) app.use((req, res) => { res.status(404).render('404', { page_title: "Oops! Page Not Found" }); });
Important Notes
- Always set the 404 status code: Using
res.status(404)tells browsers and search engines that this is an actual missing page, not a successful response. - Custom 404 View: Make sure you have a
404.ejs(or whatever template engine you're using) in yourviewsdirectory. You can style it to match your app's design for a better user experience. - Fix the typo in your existing code: In your
/viewRegistrationroute, you haveResponse.writeHead(404);— this should beres.status(404)(using the request-specificresobject), otherwise it might cause errors. Update that section to something like:if (err) { return res.status(404).render('404', { page_title: "Error Fetching Data" }); }
That's it! Now any undefined routes like /homy will be caught and redirected to your 404 page.
内容的提问来源于stack exchange,提问作者Gianluca
相关产品推荐
相关产品推荐

