如何在Express中添加404错误页面
Express.js是一个强大的node.js框架。这个框架的一个主要优点是可以定义不同的路由或中间件来处理客户端的不同请求。在本文中,我们将讨论如何通过express服务器添加404错误页面,即找不到页面。404是服务器上表示找不到的状态码。
安装模块: 使用以下命令安装所需模块。
npm install express
项目结构: 它将如下所示。
index.js
// Requiring module
const express = require("express")
const app = express()
// Handling GET /hello request
app.get("/hello", (req, res, next) => {
res.send("This is the hello response");
})
// Handling non matching request from the client
app.use((req, res, next) => {
res.status(404).send(
"<h1>Page not found on the server</h1>")
})
// Server setup
app.listen(3000, () => {
console.log("Server is Running")
})
运行 index.js 文件,请使用以下命令:
node index.js
输出:
现在打开你的浏览器并访问 http://localhost:3000/ ,服务器将返回找不到页面的响应。