下面我将从 Web 开发、命令行工具 和 浏览器 三个主要场景,详细说明如何返回 404 状态码。

Web 开发(后端/API)
这是最核心的场景,当用户或另一个程序请求一个不存在的资源时,你的服务器应该返回一个 404 响应。
通用原则
一个标准的 404 响应应该包含:
- 状态码:
404 Not Found - 响应头:
Content-Type通常设置为text/html(用于网页)或application/json(用于 API)。 - 响应体: 一段解释性的文本或 HTML,告诉客户端资源未找到。
具体实现方法(按语言/框架分类)
Node.js (Express)
Express 是 Node.js 最流行的框架之一,处理 404 非常简单。
直接发送响应

const express = require('express');
const app = express();
app.get('/api/users/123', (req, res) => {
res.send('获取用户 123 的信息');
});
// 如果请求路径没有匹配到任何路由,Express 会默认返回 404。
// 你可以自定义一个 404 处理器,它应该放在所有路由的最后。
app.use((req, res) => {
// 设置状态码
res.status(404).send('抱歉,您访问的页面不存在!');
});
app.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
使用 res.sendStatus (更简洁)
app.use((req, res) => {
// Express 会自动设置状态码和响应体(如 "Not Found")
res.sendStatus(404);
});
Python (Flask)
Flask 是一个轻量级的 Python Web 框架。
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/products/456')
def get_product():
return {"name": "Product 456", "price": 99.99}
@app.errorhandler(404)
def not_found_error(error):
# 对于 API,通常返回 JSON 格式的错误信息
return jsonify({"error": "Resource not found"}), 404
if __name__ == '__main__':
app.run(debug=True)
在这个例子中,任何不存在的路由都会触发 @app.errorhandler(404) 装饰的函数。
Python (Django)
Django 是一个功能更全面的 Python 框架,它的 404 处理方式更结构化。

-
在
urls.py中捕获 404: Django 的path()和re_path()会自动处理不存在的 URL,并抛出 404 异常。 -
创建
html模板: 在你的templates目录下创建一个html文件,当发生 404 错误时,Django 会自动渲染这个模板。<!-- templates/404.html --> <!DOCTYPE html> <html> <head> <title>Page not found</title> </head> <body> <h1>404 - Page Not Found</h1> <p>抱歉,您请求的页面不存在。</p> </body> </html> -
在视图中手动触发 404: 如果你在视图中判断资源不存在,可以手动抛出异常。
from django.http import Http404 from django.shortcuts import render def user_detail(request, user_id): try: user = User.objects.get(pk=user_id) except User.DoesNotExist: # 手动触发 404 raise Http404("用户不存在") return render(request, 'user_detail.html', {'user': user})
Java (Spring Boot)
Spring Boot 提供了非常灵活的异常处理机制。
使用 @ResponseStatus 注解
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;
@RestController
public class UserController {
@GetMapping("/api/users/{id}")
public User getUser(@PathVariable Long id) {
// 假设这里从数据库查找用户
User user = userService.findById(id);
if (user == null) {
// 如果用户不存在,抛出异常
throw new UserNotFoundException(id);
}
return user;
}
}
// 自定义异常类
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long id) {
super("User with ID " + id + " not found");
}
}
使用 @ControllerAdvice 全局处理
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public String handleUserNotFound(UserNotFoundException ex) {
return ex.getMessage(); // 返回异常信息作为响应体
}
}
PHP (Laravel)
Laravel 路由定义在 routes/web.php 或 routes/api.php 中,如果一个 URL 没有被任何路由匹配,Laravel 会自动返回 404。
你也可以手动返回 404:
// 在控制器方法中
public function show($id)
{
$user = User::find($id);
if (!$user) {
// abort() 是 Laravel 提供的辅助函数
abort(404, '用户未找到');
}
return view('user.profile', ['user' => $user]);
}
命令行工具
当你使用 curl、wget 等命令行工具访问一个 URL 时,它们会显示服务器的状态码。
使用 curl
curl -I 或 curl -i 可以只获取响应头或获取完整的响应头和响应体,其中就包含状态码。
# 访问一个不存在的页面 curl -I http://example.com/non-existent-page # 输出结果(示例) HTTP/1.1 404 Not Found Date: Wed, 27 Oct 2025 10:00:00 GMT Server: Apache/2.4.41 (Ubuntu) Content-Type: text/html; charset=UTF-8 ...
你也可以让 curl 在遇到 404 时直接退出并返回错误码:
# --fail 选项 curl --fail http://example.com/non-existent-page # 如果返回 404,curl 不会输出 HTML 错误页面,而是直接退出,退出码为 22。 # 你可以通过 $? 检查上一个命令的退出码 echo $? # 输出: 22
浏览器
当你直接在浏览器地址栏输入一个不存在的 URL 时,浏览器会接收并显示服务器返回的 404 响应。
- 服务器返回 HTML:浏览器会渲染这个 HTML 页面,显示一个 "404 Not Found" 的错误页面,很多网站会自定义这个页面,使其更美观,并提供返回首页的链接。
- 服务器返回 JSON:浏览器不会直接显示 JSON,它会尝试下载这个 JSON 文件,或者在开发者工具的 "Network" 面板中看到响应内容,这对于 API 调用是正常的。
| 场景 | 核心方法 | 示例 |
|---|---|---|
| Web 开发 | 使用框架提供的功能手动设置状态码或捕获异常。 | res.status(404).send(...) (Express)raise Http404 (Django)abort(404) (Laravel) |
| 命令行 | 使用 curl 或 wget 等工具,并查看其输出。 |
curl -I http://example.com/404 |
| 浏览器 | 直接访问不存在的 URL,浏览器会自动处理并显示结果。 | 在地址栏输入 http://somesite.com/missing-page |
选择哪种方法取决于你当前正在使用的工具和环境,核心思想是:当资源不存在时,明确告知客户端(无论是浏览器、其他服务器还是脚本)状态码为 404。
