审查生成的条件式资料处理器

来自 HTTP 语义
Node 24 进阶 10分钟 找出 4处问题

在这个生成式处理器通过代理提供私有资料前,对它进行审查。

为一份私有资料处理 GET 请求,支持符合标准的 ETag 验证,在 304 中不返回内容,先拒绝其他方法再访问存储,并防止共享缓存复用。

JavaScript
import { createHash } from "node:crypto";
async function sendProfile(request, response, profileId) {
  const profile = await store.find(profileId);
  if (request.method !== "GET") {
    response.writeHead(405, { Allow: "GET" }).end();
    return;
  }
  if (!profile) {
    response.writeHead(404).end();
    return;
  }
  const body = JSON.stringify(profile);
  const digest = createHash("sha256").update(body).digest("hex");
  const etag = `"${digest}"`;
  if (request.headers["if-none-match"] === etag) {
    response.writeHead(304, { ETag: etag });
    response.end(body);
    return;
  }
  response.writeHead(200, {
    ETag: etag,
    "Content-Type": "application/json",
    "Cache-Control": "public, max-age=3600",
  }).end(body);
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误