示例工程 22-security-service-worker
22-security-service-worker/01-cors-modes/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— CORS 预检与凭证的判定模型
const SIMPLE_METHODS = ['GET', 'HEAD', 'POST'];
const SIMPLE_HEADERS = ['accept', 'accept-language', 'content-language', 'content-type'];
export function corsDecision({ sameOrigin, method = 'GET', headers = {}, credentials = false }) {
if (sameOrigin) {
return { preflight: false, allowOrigin: 'same-origin', readable: true };
}
const methodSafe = SIMPLE_METHODS.includes(method.toUpperCase());
const headersSafe = Object.keys(headers).every((h) => SIMPLE_HEADERS.includes(h.toLowerCase()));
const preflight = !methodSafe || !headersSafe;
return {
preflight,
allowOrigin: credentials ? 'exact-origin' : '*',
readable: true,
};
}
export async function run(log = console.log) {
if (typeof document === 'undefined') {
throw new Error('本示例需要浏览器环境:请通过 index.html 打开');
}
const res = await fetch('./index.html', { method: 'GET' });
log(`同源 GET 状态:${res.status},type=${res.type}`);
log(`同源请求不需要预检:${JSON.stringify(corsDecision({ sameOrigin: true }))}`);
log(`跨源 PUT + JSON:${JSON.stringify(corsDecision({ sameOrigin: false, method: 'PUT', headers: { 'content-type': 'application/json' } }))}`);
log(`跨源带凭证:allow-origin 必须回显具体源,不能是 *。`);
return { status: res.status, type: res.type };
}