共用方式為


教學課程:設定 CORS Proxy 伺服器來管理原生驗證的 CORS 標頭 (預覽)

適用於:白色圓圈中帶有灰色 X 符號。 租戶 綠色圓圈及白色勾選符號。 外部租戶(深入了解

在本教學課程中,您會瞭解如何設定 CORS Proxy 伺服器來管理 CORS 標頭,同時從 React 單頁應用程式與原生驗證 API 互動(SPA)。 CORS Proxy 伺服器是原生驗證 API 無法支援 跨原始來源資源分享 (CORS)的解決方案。

在本教學課程中,您會:

  • 建立 CORS Proxy 伺服器。
  • 設定 CORS Proxy 伺服器以呼叫原生驗證 API。
  • 執行及測試您的 React 應用程式。

先決條件

建立 CORS Proxy 伺服器

  1. 在 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);
    });
    
  2. 在 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;
    
    • 尋找佔位符 Enter_the_Tenant_Subdomain_Here,並將其替換為目錄租戶子域名。 例如,如果您的租戶主要網域是 contoso.onmicrosoft.com,請使用 contoso。 如果您沒有租戶子域,請瞭解如何查看租戶詳細資料。

    • tenantId,然後用目錄(租戶)ID替換它。 如果您沒有租戶 ID,請瞭解如何 查看租戶詳細資訊

  3. 開啟 package.json 檔案,然後在 文稿 物件中新增下列命令:

    "cors": "node cors.js",
    

此時,React 應用程式和 CORS Proxy 伺服器已準備好執行。

執行及測試您的應用程式

  1. 開啟終端機視窗並瀏覽至您應用程式的根資料夾:

    cd reactspa
    
  2. 若要啟動 CORS Proxy 伺服器,請在終端機中執行下列命令:

    npm run cors
    
  3. 若要啟動 React 應用程式,請開啟另一個終端機視窗,然後執行下列命令:

    cd reactspa
    npm start
    
  4. 開啟網頁瀏覽器並瀏覽至 http://localhost:3000/。 註冊表單會出現。

  5. 若要註冊帳戶,請輸入詳細數據,選取 [註冊] 按鈕,然後遵循提示。

此時,您已成功建立 React 應用程式,其可使用原生驗證 API 來註冊使用者。 接下來,您可以更新 React 應用程式以登入使用者或重設使用者的密碼。

CORS Proxy 伺服器的其他資訊

在本教學課程中,您會設定本機 CORS 伺服器。 不過,您可以 使用 Azure 函數應用程式來設定反向代理伺服器來管理 CORS 標頭,如測試環境中所述,

在生產環境中,您可以使用 使用 Azure 函式應用程式設定原生驗證 API 的單頁應用程式反向代理的步驟 來設定您的 CORS Proxy 伺服器。