You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 your views directory. You can style it to match your app's design for a better user experience.
  • Fix the typo in your existing code: In your /viewRegistration route, you have Response.writeHead(404); — this should be res.status(404) (using the request-specific res object), 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 17:07:30