安全
H3 安全工具。
认证
basicAuth(opts)
创建一个基本认证中间件。
示例:
import { H3, serve, basicAuth } from "h3";
const auth = basicAuth({ password: "test" });
app.get("/", (event) => `Hello ${event.context.basicAuth?.username}!`, [auth]);
serve(app, { port: 3000 });
requireBasicAuth(event, opts)
为当前请求应用基本认证。
示例:
import { defineHandler, requireBasicAuth } from "h3";
export default defineHandler(async (event) => {
await requireBasicAuth(event, { password: "test" });
return `Hello, ${event.context.basicAuth.username}!`;
});
会话
clearSession(event, config)
清除当前请求的会话数据。
getSession(event, config)
获取当前请求的会话。
sealSession(event, config)
加密并签名当前请求的会话数据。
unsealSession(_event, config, sealed)
解密并验证当前请求的会话数据。
updateSession(event, config, update?)
更新当前请求的会话数据。
useSession(event, config)
为当前请求创建一个会话管理器。
指纹
getRequestFingerprint(event, opts)
获取传入请求的唯一指纹。
跨域资源共享(CORS)
appendCorsHeaders(event, options)
向响应中添加 CORS 头。
appendCorsPreflightHeaders(event, options)
向响应中添加 CORS 预检请求头。
handleCors(event, options)
处理传入请求的 CORS。
如果传入请求是 CORS 预检请求,将添加 CORS 预检请求头并发送 204 响应。
如果返回值为 true
,表示请求已被处理,无需进一步操作。
示例:
const app = new H3();
const router = createRouter();
router.use("/", async (event) => {
const corsRes = handleCors(event, {
origin: "*",
preflight: {
statusCode: 204,
},
methods: "*",
});
if (corsRes) {
return corsRes;
}
// 你的代码在此
});
isCorsOriginAllowed(origin, options)
检查来源是否被允许。
isPreflightRequest(event)
检查传入请求是否为 CORS 预检请求。