适用于: 员工租户
外部租户(了解详细信息)
本教程介绍如何在从 React 单页应用 (SPA) 与本机身份验证 API 交互时设置 CORS 代理服务器来管理 CORS 标头。 如果本机身份验证 API 无法支持跨源资源共享 (CORS),解决方案是使用 CORS 代理服务器。
在本教程中,你将:
- 创建 CORS 代理服务器。
- 设置 CORS 代理服务器以调用本机身份验证 API。
- 运行并测试 React 应用。
先决条件
- 完成 教程中的步骤:创建 React 单页应用,以使用本机身份验证 API将用户登录到外部租户。
创建 CORS 代理服务器
在 React 应用的根文件夹中,创建名为 cors.js的文件,然后添加以下代码:
const http = require("http"); const https = require("https"); const url = require("url"); const proxyConfig = require("./proxy.config.js"); http .createServer((req, res) => { const reqUrl = url.parse(req.url); const domain = url.parse(proxyConfig.proxy).hostname; 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 proxyReq = https.request( targetUrl, { method: req.method, headers: { ...req.headers, host: domain, }, }, (proxyRes) => { res.writeHead(proxyRes.statusCode, { ...proxyRes.headers, "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization", }); 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); });
在 React 应用的根文件夹中,创建名为 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;
打开 package.json 文件,然后在 脚本 对象中添加以下命令:
"cors": "node cors.js",
此时,React 应用和 CORS 代理服务器已准备好运行。
运行并测试应用
打开终端窗口并导航到应用的根文件夹:
cd reactspa
若要启动 CORS 代理服务器,请在终端中运行以下命令:
npm run cors
若要启动 React 应用,请打开另一个终端窗口,然后运行以下命令:
cd reactspa npm start
打开 Web 浏览器并导航到
http://localhost:3000/
。 此时会显示注册表单。若要注册帐户,请输入详细信息,选择 注册 按钮,然后按照提示作。
此时,你已成功创建了一个 React 应用,该应用可以使用本机身份验证 API 注册用户。 接下来,可以更新 React 应用以登录用户或重置用户的密码。
有关 CORS 代理服务器的其他信息
在本教程中,将设置本地 CORS 服务器。 但是,可以使用 Azure 函数应用设置反向代理服务器来管理 CORS 标头,如测试环境中所述。
在生产环境中,您可以使用 中的步骤,通过 Azure Function App 为使用本机身份验证 API 的单页应用设置反向代理,从而配置您的 CORS 代理服务器。
相关内容
- 教程:使用本机身份验证将用户登录到 React 单页应用应用。
- 教程:使用本机身份验证在 React 单页应用应用中重置密码。