跳转到内容

Content Negotiation

negotiate 函数解析 Accept 请求头,按质量因子(q 值)排序后匹配服务端支持的响应类型。

import { negotiate } from "@ventostack/core";
const result = negotiate(ctx.headers.get("accept"));
// { type: "json", contentType: "application/json" }
switch (result.type) {
case "json":
return ctx.json(data);
case "html":
return ctx.html(renderHTML(data));
case "text":
return ctx.text(formatText(data));
case "xml":
return ctx.text(renderXML(data), 200, { "Content-Type": result.contentType });
}
// 仅支持 JSON 和 HTML
const result = negotiate(acceptHeader, ["json", "html"]);
类型标识Content-Type
jsonapplication/json
htmltext/html; charset=utf-8
texttext/plain; charset=utf-8
xmlapplication/xml
  1. 解析 Accept 头,按 q 值降序排列
  2. 精确匹配 MIME 类型
  3. 通配符匹配(如 text/*
  4. 无匹配或 */* 时默认返回 JSON
function negotiate(
acceptHeader: string | null,
supported?: Array<"json" | "html" | "text" | "xml">,
): NegotiationResult;
属性类型说明
type"json" | "html" | "text" | "xml"匹配的响应类型
contentTypestring对应的 Content-Type 值