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 });}指定支持的类型
Section titled “指定支持的类型”// 仅支持 JSON 和 HTMLconst result = negotiate(acceptHeader, ["json", "html"]);支持的媒体类型
Section titled “支持的媒体类型”| 类型标识 | Content-Type |
|---|---|
json | application/json |
html | text/html; charset=utf-8 |
text | text/plain; charset=utf-8 |
xml | application/xml |
- 解析
Accept头,按q值降序排列 - 精确匹配 MIME 类型
- 通配符匹配(如
text/*) - 无匹配或
*/*时默认返回 JSON
function negotiate( acceptHeader: string | null, supported?: Array<"json" | "html" | "text" | "xml">,): NegotiationResult;NegotiationResult
Section titled “NegotiationResult”| 属性 | 类型 | 说明 |
|---|---|---|
type | "json" | "html" | "text" | "xml" | 匹配的响应类型 |
contentType | string | 对应的 Content-Type 值 |