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

如何在Express应用中正确返回404 Not Found页面?

解决Express 404页面展示及API废弃警告问题

首先处理IDE提示的废弃API警告:原代码中res.send('404', body)的写法已被Express废弃,需改为res.status(404).xxx()的形式,再根据需求渲染404页面,以下是几种实现方式:

方式一:使用模板引擎(推荐,支持动态数据)

以常用的EJS模板为例:

  1. 安装EJS依赖
npm install ejs
  1. 在Express应用中配置模板引擎和视图目录
const path = require('path');
const express = require('express');
const app = express();

// 设置模板引擎为EJS
app.set('view engine', 'ejs');
// 指定视图文件存放目录(假设视图文件在项目根目录的views文件夹下)
app.set('views', path.join(__dirname, 'views'));
  1. 在views目录下创建404.ejs模板文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= title %> - Page Not Found</title>
</head>
<body>
    <div class="error-container">
        <h1><%= title %></h1>
        <p><%= errorMessage %></p>
        <p>Created by <%= name %></p>
    </div>
</body>
</html>
  1. 修改404路由,渲染模板页面
app.get('*', (req, res) => {
    res.status(404).render('404', {
        title: 404,
        name: 'James Olaleye',
        errorMessage: 'Page not found'
    });
});

方式二:直接发送HTML字符串

无需依赖模板引擎,直接构造HTML内容返回:

app.get('*', (req, res) => {
    const errorHtml = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>404 - Page Not Found</title>
        </head>
        <body>
            <h1>404</h1>
            <p>Page not found</p>
            <p>Created by James Olaleye</p>
        </body>
        </html>
    `;
    res.status(404).send(errorHtml);
});

方式三:发送静态HTML文件

若已有现成的静态404页面文件:

  1. 将404.html放在项目的public目录下(需先配置静态资源目录)
app.use(express.static(path.join(__dirname, 'public')));
  1. 修改路由返回静态文件
app.get('*', (req, res) => {
    res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));
});

内容的提问来源于stack exchange,提问作者James Olaleye

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:55:15