Node.js日志中的HTTP状态码含义
状态码分类概览
常见HTTP状态码速查表
| 状态码 | 含义 | 常见原因与排查要点 |
|---|---|---|
| 200 | OK | 请求成功,返回了预期数据。 |
| 201 | Created | 资源创建成功,多见于 POST/PUT。检查数据库写入与返回位置头。 |
| 204 | No Content | 成功但无内容,多见于 DELETE。确认业务是否应返回内容。 |
| 301 | Moved Permanently | 资源永久迁移。更新站点地图与反向代理/CDN配置。 |
| 302 | Found | 资源临时迁移。检查是否应改用 307/308 保留方法。 |
| 304 | Not Modified | 资源未修改,使用缓存。确认 ETag/Last-Modified 与缓存策略。 |
| 400 | Bad Request | 请求语法/参数错误。校验请求体、查询参数、Content-Type。 |
| 401 | Unauthorized | 未认证。检查认证中间件、Token 是否有效与过期。 |
| 403 | Forbidden | 已认证但无权限。核对角色/权限策略与资源 ACL。 |
| 404 | Not Found | 路由或资源不存在。核对路由表、静态资源路径、数据库记录。 |
| 405 | Method Not Allowed | 方法不被允许。核对路由允许的 GET/POST/PUT/DELETE 等。 |
| 408 | Request Timeout | 请求超时。检查客户端超时设置与服务器处理耗时。 |
| 500 | Internal Server Error | 服务器内部错误。查看异常堆栈、未捕获异常与依赖故障。 |
| 502 | Bad Gateway | 网关/代理从上游收到无效响应。检查上游服务健康与网络。 |
| 503 | Service Unavailable | 服务暂不可用。关注过载、维护、连接池/线程耗尽。 |
| 504 | Gateway Timeout | 网关/代理等待上游超时。优化上游响应时间或调整超时阈值。 |
| 以上状态码及其含义为 Web 通用标准,Node.js 只是按标准返回与记录,便于定位问题。 |
在Node.js中如何设置与记录状态码
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/ok') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('OK');
} else if (req.url === '/error') {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('Server listening on http://localhost:3000');
});
const express = require('express');
const app = express();
app.get('/example', (req, res) => {
if (/* 资源不存在 */) {
console.warn(`[WARN] 404 | ${req.method} ${req.url}`);
return res.status(404).send('Not Found');
}
res.status(200).send('OK');
});
// 统一错误处理中间件
app.use((err, req, res, next) => {
console.error(`[ERROR] ${err.stack || err}`);
res.status(500).send('Internal Server Error');
});
app.listen(3000, () => console.log('Server started'));
上述方式可确保在日志中输出准确的 HTTP 状态码,便于快速定位问题。
与网络或系统错误码的区别