利用沙箱解决跨域问题
Published on July 4, 2024Updated on July 4, 2024
Loading content...
/etc/hosts
CODE127.0.0.1 a.local.com 127.0.0.1 b.cors.com
TypeScriptconst allowedOrigins = ["http://b.cors.com:3002"]; async function bootstrap() { const app = await NestFactory.create<NestExpressApplication>(AppModule); let cnt = 0; app.enableCors({ origin: (origin, callback) => { console.log("origin: ", origin, cnt++); if (!origin || allowedOrigins.includes(origin)) { callback(null, true); return; } callback(null, false); }, }); // 托管静态文件 app.useStaticAssets(join(__dirname, "..", "static", "father"), { prefix: "/a", }); app.useStaticAssets(join(__dirname, "..", "static", "child"), { prefix: "/b", }); await app.listen(3002); }
cors 仅仅 让 b.cors.com 过
The contentWindow
property returns the Window object of an HTMLIFrameElement.
JavaScriptpostMessage(message, targetOrigin);
JavaScriptconst iframe = document.getElementById("childIframe"); document.getElementById("sendToChild").addEventListener("click", async () => { iframe.contentWindow.postMessage( { source: "XxxUniqueID", data: 66, }, "*" ); }); window.addEventListener("message", async (event) => { if (event.data?.source === "XxxUniqueID") { console.log("[Father] Received message from parent:", event.data.data); } });
JavaScriptwindow.addEventListener("message", async (event) => { if (event.data?.source === "XxxUniqueID") { console.log("[Child] Received message from parent:", event.data.data); window.parent.postMessage( { source: "XxxUniqueID", data: "Hello from Child!" }, "*" ); } });
TypeScriptdocument .getElementById("requestButtonUseIframe") .addEventListener("click", async () => { // 利用 iframe 发送请求 iframe.contentWindow.postMessage( { source: "XxxUniqueID", type: "Request", data: { endpoint: "http://localhost:3002/", }, }, "*" ); });
TypeScriptwindow.addEventListener("message", async (event) => { if (event.data?.source !== "XxxUniqueID") { return; } const { type, data: eventData } = event.data; console.log("[Child] Received message from parent:", event.data.data); switch (type) { case "Request": { try { const res = await fetch(eventData.endpoint, { method: "GET", }); const data = await res.text(); console.log("[Child] Response:", data); window.parent.postMessage({ source: "XxxUniqueID", data }, "*"); } catch (error) { console.error("[Child] Error:", error); } } break; default: break; } });
目前基本流程跑通了
还有问题
解法