简体   繁体   English

如何在 Node/Express 中设置 404 路由

[英]How to setup a 404 route in Node/Express

How do I set up a 404 route in Node/Express?如何在 Node/Express 中设置 404 路由? If the URL is not valid, I want to render an HTML or Handlebars file to the client如果 URL 无效,我想向客户端呈现 HTML 或 Handlebars 文件

lets say you have an express app like this:假设您有一个这样的 Express 应用程序:

const app = express()

then put all your routes and at the end of all your routes put 404 route like:然后放置所有路线,并在所有路线的末尾放置 404 路线,例如:

 app.use((req, res) => { res.status(404).json({ success: false, message: "Page not found", }); });

if you are using handlbars or any other template engine, you can do it like:如果您使用的是 handlbars 或任何其他模板引擎,您可以这样做:

 app.use((req, res) => { res.render('404.html') });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM