"use strict";
const output = document.querySelector("#output");
function show(label, value) {
let text;
if (typeof value === "undefined") text = "undefined";
else if (typeof value === "number" && !Number.isFinite(value)) text = String(value);
else if (typeof value === "string") text = value;
else text = JSON.stringify(value);
output.textContent += label + ": " + text + "\n";
}
fetch("http://127.0.0.1:9001/cors-data.php")
.then(response => {
if (!response.ok) throw new Error("HTTP " + response.status);
return response.json();
})
.then(data => show("名称", data.name))
.catch(error => show("请求失败", error.message));
本例需在 9000和9001独立HTTP服务;服务端允许准确Origin;不使用file协议 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:9000和9001独立HTTP服务;服务端允许准确Origin;不使用file协议
入口文件:examples/9c64781ee2f178425a4b4ea6/cors-fetch/index.html
本例采用完整 HTML 文档,样式和脚本在 HTML 源码中维护。
预期结果与验证条件观察提示
- 从9000打开cors-client.html,9001仅允许此Origin时得到名称
- 换为其他Origin应受到浏览器读取限制
- 服务未启动、CORS不符合或JSON不合法时进入失败分支
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联11章) · 含当前章节或实例 · mbskycom202611a250.zip
课程关联工程包(登记关联11章) · 含当前章节或实例 · mbskycom202611a438.zip