適用於:
外部租用戶 (深入瞭解)
在本指南中,您將瞭解如何設定本機 CORS Proxy 伺服器來管理 CORS 標頭,同時從單頁應用程式與原生驗證 API 互動(SPA)。 CORS Proxy 伺服器是原生驗證 API 無法支援 跨原始來源資源分享 (CORS)的解決方案。
您可以使用本文中設定的 CORS 伺服器進行本機應用程式開發。 或者:
- 您可以針對測試環境 使用 Azure 函式應用程式,設定反向 Proxy 伺服器來管理 CORS 標頭 。
- 在生產環境中,您可以使用 Azure Front Door 作為反向 Proxy。
建立 CORS Proxy 伺服器
在 SPA 的根資料夾中,建立名為 cors.js的檔案,然後新增下列程式代碼:
const http = require("http"); const https = require("https"); const url = require("url"); const proxyConfig = require("./proxy.config"); const extraHeaders = [ "x-client-SKU", "x-client-VER", "x-client-OS", "x-client-CPU", "x-client-current-telemetry", "x-client-last-telemetry", "client-request-id", ]; http.createServer((req, res) => { const reqUrl = url.parse(req.url); const domain = url.parse(proxyConfig.proxy).hostname; // Set CORS headers for all responses including OPTIONS const corsHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization, " + extraHeaders.join(", "), "Access-Control-Allow-Credentials": "true", "Access-Control-Max-Age": "86400", // 24 hours }; // Handle preflight OPTIONS request if (req.method === "OPTIONS") { res.writeHead(204, corsHeaders); res.end(); return; } if (reqUrl.pathname.startsWith(proxyConfig.localApiPath)) { const targetUrl = proxyConfig.proxy + reqUrl.pathname?.replace(proxyConfig.localApiPath, "") + (reqUrl.search || ""); console.log("Incoming request -> " + req.url + " ===> " + reqUrl.pathname); const newHeaders = {}; for (let [key, value] of Object.entries(req.headers)) { if (key !== 'origin') { newHeaders[key] = value; } } const proxyReq = https.request( targetUrl, { method: req.method, headers: { ...newHeaders, host: domain, }, }, (proxyRes) => { res.writeHead(proxyRes.statusCode, { ...proxyRes.headers, ...corsHeaders, }); proxyRes.pipe(res); } ); proxyReq.on("error", (err) => { console.error("Error with the proxy request:", err); res.writeHead(500, { "Content-Type": "text/plain" }); res.end("Proxy error."); }); req.pipe(proxyReq); } else { res.writeHead(404, { "Content-Type": "text/plain" }); res.end("Not Found"); } }).listen(proxyConfig.port, () => { console.log("CORS proxy running on http://localhost:3001"); console.log("Proxying from " + proxyConfig.localApiPath + " ===> " + proxyConfig.proxy); });在 SPA 的根資料夾中,建立名為 proxy.config.js的檔案,然後新增下列程式代碼:
const tenantSubdomain = "Enter_the_Tenant_Subdomain_Here"; const tenantId = "Enter_the_Tenant_Id_Here"; const config = { localApiPath: "/api", port: 3001, proxy: `https://${tenantSubdomain}.ciamlogin.com/${tenantId}`, }; module.exports = config;開啟 SPA 的package.json 檔案,然後在 scripts 物件中新增下列命令:
"cors": "node cors.js",
此時,CORS Proxy 伺服器已準備好執行。
執行 CORS 伺服器
若要啟動 CORS Proxy 伺服器,請在終端機中執行下列命令:
npm run cors
相關內容
- 教學課程:使用原生驗證,讓使用者登入 React 單頁應用程式。
- 教學課程:使用原生驗證在 React 單頁應用程式應用程式中重設密碼。