适用于:
外部租户(了解详细信息)
本指南介绍如何设置本地 CORS 代理服务器以管理 CORS 标头,同时从单页应用(SPA)与本机身份验证 API 交互。 如果本机身份验证 API 无法支持 跨源资源共享 (CORS),解决方案是 CORS 代理服务器。
可以使用本文中设置的 CORS 服务器进行本地应用开发。 另一方面:
- 可以通过对测试环境 使用 Azure Function App 设置反向代理服务器来管理 CORS 标头 。
- 在生产环境中,可以使用 Azure Front Door 作为反向代理。
创建 CORS 代理服务器
在 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 文件,然后在 脚本 对象中添加以下命令:
"cors": "node cors.js",
此时,CORS 代理服务器已准备好运行。
运行 CORS 服务器
若要启动 CORS 代理服务器,请在终端中运行以下命令:
npm run cors
相关内容
- 教程:使用本机身份验证将用户登录到 React 单页应用应用。
- 教程:使用本机身份验证在 React 单页应用应用中重置密码。