# 每位开发者都应了解的重要 HTTP 响应头

发布: (2025年12月25日 GMT+8 23:11)
7 min read
原文: Dev.to

Source: Dev.to

为什么 HTTP 头对后端开发者很重要

HTTP 头是随每个服务器响应一起发送的元数据。它们告诉浏览器如何:

  • 缓存资源 – 提升性能。
  • 强制安全策略 – 保护你的应用。
  • 处理内容 – 塑造用户体验。

配置错误的头可能导致漏洞、加载缓慢或功能失效。让我们来修复它们。

1. Content-Type & Content-Disposition

Purpose – 告诉浏览器你发送的数据类型以及如何处理它。

DirectiveDescription
Content-TypeMIME 类型(例如 application/jsontext/htmlapplication/pdf)。
Content-Dispositioninline(在浏览器中显示)或 attachment(强制下载)。

Example (raw TCP server)

import { open } from "node:fs/promises";
import net from "node:net";

const server = net.createServer(async (socket) => {
  const fileHandle = await open("report.pdf");
  const { size } = await fileHandle.stat();
  const readStream = fileHandle.createReadStream();

  socket.write("HTTP/1.1 200 OK\r\n");
  socket.write("Content-Type: application/pdf\r\n");
  socket.write(`Content-Length: ${size}\r\n`);
  socket.write('Content-Disposition: attachment; filename="report.pdf"\r\n');
  socket.write("\r\n");

  readStream.pipe(socket);
});

server.listen(8080);

Why it matters – 如果没有 Content-Type,浏览器可能会误解负载。没有 Content-Disposition 时,PDF 可能会在浏览器中打开,而不是按预期下载。

2. Cache-Control

Purpose – 控制浏览器缓存响应的方式和时长。

DirectiveEffect
no-store永不缓存(适用于敏感数据)。
no-cache缓存但在每次请求时重新验证。
max-age=3600缓存 1 小时。
public / private共享缓存 与 用户专用缓存。

Express.js 示例

import express from "express";

const app = express();

app.get("/api/profile", (req, res) => {
  res.set("Cache-Control", "private, no-cache");
  res.json({ user: "John Doe" });
});

app.get("/static/logo.png", (req, res) => {
  // Cache for 1 year
  res.set("Cache-Control", "public, max-age=31536000");
  res.sendFile("./logo.png");
});

app.listen(3000);

Impact – 适当的缓存可以将服务器负载降低 60‑80 %,并显著提升页面加载速度。

3. Content-Security-Policy (CSP)

Purpose – 通过限制资源加载来源来缓解 XSS 攻击。

Common Directives

default-src 'self'               // Only load from your own origin
script-src 'self' https://cdn.example.com
img-src *

Implementation (Express middleware)

app.use((req, res, next) => {
  res.set(
    "Content-Security-Policy",
    "default-src 'self'; script-src 'self' https://trusted-cdn.com; img-src *"
  );
  next();
});

Security benefit – 通过阻止内联脚本和未授权的资源加载,能够拦截约 90 % 的 XSS 攻击。

4. Strict-Transport-Security (HSTS)

Purpose – 强制浏览器始终使用 HTTPS,防止中间人攻击。

Example

app.use((req, res, next) => {
  res.set(
    "Strict-Transport-Security",
    "max-age=31536000; includeSubDomains"
  );
  next();
});
  • max-age=31536000 → 强制 HTTPS 1 年。
  • includeSubDomains → 适用于所有子域。

Critical note – 一旦设置,浏览器将在指定期限内拒绝对你的域名的纯 HTTP 连接。

5. X-Content-Type-Options

Purpose – 停止浏览器进行 MIME‑type 嗅探,防止执行恶意内容。

Usage

app.use((req, res, next) => {
  res.set("X-Content-Type-Options", "nosniff");
  next();
});

Why it’s essential – 防止包含类似 JavaScript 内容的 .txt 文件被当作脚本执行。

6. CORS 标头(跨域资源共享)

Purpose – 控制哪些外部来源可以访问您的 API。

示例

app.use((req, res, next) => {
  res.set("Access-Control-Allow-Origin", "https://myapp.com");
  res.set("Access-Control-Allow-Methods", "GET, POST, PUT");
  res.set(
    "Access-Control-Allow-Headers",
    "Content-Type, Authorization"
  );
  next();
});

Real‑world scenario – 您的 React 前端 (myapp.com) 调用 Node.js API (api.myapp.com)。如果没有这些头部,浏览器会阻止请求。

Source:

7. Set-Cookie(带安全属性)

目的 – 安全地发送会话 Cookie。

示例

app.post("/login", (req, res) => {
  res.cookie("sessionId", "abc123", {
    httpOnly: true,   // 防止 JavaScript 访问(XSS 保护)
    secure: true,     // 仅在 HTTPS 上发送
    sameSite: "strict", // CSRF 保护
    maxAge: 3600000   // 1 小时
  });
  res.json({ success: true });
});

安全影响

属性效果
httpOnly阻止客户端脚本访问 Cookie。
secureCookie 只通过 HTTPS 传输。
sameSite缓解 CSRF 攻击(strictlax)。
maxAge控制 Cookie 的生命周期。

生产环境实用检查清单

在发布之前,确认你的 Node.js 应用已设置以下响应头(或其等效的对应项):

  • Content-Type – 必须始终存在且准确。
  • Content-Disposition – 在需要下载行为的场景下使用。
  • Cache-Control – 根据不同接口进行调优(public 与 private、max‑age、no‑store 等)。
  • Content-Security-Policy – 采用仅白名单方式定义。
  • Strict-Transport-Security – 在仅 HTTPS 的服务上启用。
  • X-Content-Type-Options: nosniff
  • ✅ CORS 相关头 (Access-Control-Allow-*) – 仅在需要跨域访问的路由上返回。
  • ✅ 安全的 Set-Cookie 属性(httpOnlysecuresameSite、合适的 maxAge)。
  • Referrer-Policy – 如 no-referrer-when-downgrade 或更严格的策略,以控制引用来源泄漏。
  • Feature-Policy / Permissions-Policy – 限制强大浏览器功能的使用(例如 geolocationcamera)。
  • X-Frame-Options: DENYSAMEORIGIN – 防止点击劫持。

提示: 使用集成测试自动化检查响应头,或使用类似 helmetnpm i helmet)的中间件库,一行代码即可应用上述多数默认设置:

import helmet from "helmet";
app.use(helmet());

TL;DR

  • Headers 不是可选的 – 它们是生产级 API 的核心部分。
  • 一次性配置,频繁测试 – 小小的失误可能让你面临严重风险。
  • 利用现有中间件 (Helmet, cors, compression) 来避免重复造轮子。

现在就去让你的 Node.js 服务 安全、性能卓越且专业

✅ 推荐的 HTTP 头

  • Cache-Control – 根据内容类型设置
  • Content-Security-Policy – 阻止 XSS 攻击
  • Strict-Transport-Security – 强制使用 HTTPS
  • X-Content-Type-Options: nosniff – 防止 MIME 类型嗅探
  • CORS headers – 启用与前端的安全通信
  • Secure cookie attributes – 保护会话 Cookie(例如 HttpOnlySecureSameSite

结论

HTTP 头是你的第一道防线,也是性能优化的关键杠杆。示例——尤其是低层 net 模块的做法——表明头部只是你可以控制的字符串。无论你是使用原始 TCP 套接字还是像 Express.js 这样的框架,理解这些头部会让你成为更具安全意识和性能意识的开发者

  1. 审计 当前应用的头部,使用浏览器的 DevTools(Network 标签页)。
  2. 添加 任何缺失的安全头部——用户的数据取决于此。

接下来的步骤

  • 在以下位置测试你的头部
  • 争取获得 A+ 评级
Back to Blog

相关文章

阅读更多 »