首頁  >  文章  >  web前端  >  解決 CORS 問題的方法

解決 CORS 問題的方法

Barbara Streisand
Barbara Streisand原創
2024-10-01 06:18:29130瀏覽

Ways to resolve CORS issues

要解決CORS 問題,您需要在Web 伺服器(如Apache 或Nginx)、後端(如Django、Go 或Node.js)中新增適當的標頭,或在前端框架(如React 或Next.js)中。以下是每個平台的步驟:

1. 網路伺服器

阿帕契

您可以在 Apache 的設定檔(例如 .htaccess、httpd.conf 或 apache2.conf)或特定虛擬主機設定中設定 CORS 標頭。

新增以下行以啟用 CORS:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type, Authorization"
</IfModule>
  • 要對特定域應用 CORS:
  Header set Access-Control-Allow-Origin "https://example.com"
  • 如果需要憑證:
  Header set Access-Control-Allow-Credentials "true"

確保 mod_headers 模組已啟用。如果沒有,請使用以下命令啟用它:

sudo a2enmod headers
sudo systemctl restart apache2

Nginx

在 Nginx 中,您可以在 nginx.conf 或特定伺服器區塊中設定 CORS 標頭。

新增以下行:

server {
    location / {
        add_header Access-Control-Allow-Origin "*";
        add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
        add_header Access-Control-Allow-Headers "Content-Type, Authorization";
    }

    # Optional: Add for handling preflight OPTIONS requests
    if ($request_method = OPTIONS) {
        add_header Access-Control-Allow-Origin "*";
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS, PUT, DELETE";
        add_header Access-Control-Allow-Headers "Authorization, Content-Type";
        return 204;
    }
}
  • 如果需要憑證:
  add_header Access-Control-Allow-Credentials "true";

然後重新啟動Nginx:

sudo systemctl restart nginx

2. 後端框架

姜戈

在 Django 中,您可以使用 django-cors-headers 套件新增 CORS 標頭。

  1. 安裝包:
   pip install django-cors-headers
  1. 將「corsheaders」加入 settings.py 中的 INSTALLED_APPS 中:
   INSTALLED_APPS = [
       ...
       'corsheaders',
   ]
  1. 將 CORS 中間件加入您的中間件:
   MIDDLEWARE = [
       'corsheaders.middleware.CorsMiddleware',
       'django.middleware.common.CommonMiddleware',
       ...
   ]
  1. 在settings.py中設定允許的來源:
   CORS_ALLOWED_ORIGINS = [
       "https://example.com",
   ]
  • 允許所有來源:
  CORS_ALLOW_ALL_ORIGINS = True
  • 如果需要憑證:
  CORS_ALLOW_CREDENTIALS = True
  • 允許特定的標頭或方法:
  CORS_ALLOW_HEADERS = ['Authorization', 'Content-Type']
  CORS_ALLOW_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']

Go(Go 語)

在 Go 中,您可以在 HTTP 處理程序中手動處理 CORS,或使用像 rs/cors 這樣的中間件。

使用 rs/cors 中介軟體:

  1. 安裝包:
   go get github.com/rs/cors
  1. 在您的應用程式中使用它:
   package main

   import (
       "net/http"
       "github.com/rs/cors"
   )

   func main() {
       mux := http.NewServeMux()

       // Example handler
       mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
           w.Write([]byte("Hello, World!"))
       })

       // CORS middleware
       handler := cors.New(cors.Options{
           AllowedOrigins:   []string{"https://example.com"}, // Or use * for all
           AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
           AllowedHeaders:   []string{"Authorization", "Content-Type"},
           AllowCredentials: true,
       }).Handler(mux)

       http.ListenAndServe(":8080", handler)
   }

Node.js (Express)

在 Express (Node.js) 中,您可以使用 cors 中間件。

  1. 安裝cors套件:
   npm install cors
  1. 在 Express 應用中加入中間件:
   const express = require('express');
   const cors = require('cors');
   const app = express();

   // Enable CORS for all routes
   app.use(cors());

   // To allow specific origins
   app.use(cors({
       origin: 'https://example.com',
       methods: ['GET', 'POST', 'PUT', 'DELETE'],
       allowedHeaders: ['Authorization', 'Content-Type'],
       credentials: true
   }));

   // Example route
   app.get('/', (req, res) => {
       res.send('Hello World');
   });

   app.listen(3000, () => {
       console.log('Server running on port 3000');
   });

3. 前端框架

反應

在 React 中,CORS 由後端處理,但在開發過程中,您可以代理 API 請求以避免 CORS 問題。

  1. 為 package.json 新增代理:
   {
     "proxy": "http://localhost:5000"
   }

這將在開發期間將請求代理到在連接埠 5000 上執行的後端伺服器。

對於生產,後端應該處理 CORS。如有需要,請使用 http-proxy-middleware 等工具進行更多控制。

Next.js

在 Next.js 中,您可以在 API 路由中設定 CORS。

  1. 為 API 路由建立自訂中間件:
   export default function handler(req, res) {
       res.setHeader('Access-Control-Allow-Origin', '*'); // Allow all origins
       res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
       res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type');

       if (req.method === 'OPTIONS') {
           // Handle preflight request
           res.status(200).end();
           return;
       }

       // Handle the actual request
       res.status(200).json({ message: 'Hello from Next.js' });
   }
  1. 在next.config.js中,您也可以修改回應頭:
   module.exports = {
       async headers() {
           return [
               {
                   source: '/(.*)', // Apply to all routes
                   headers: [
                       {
                           key: 'Access-Control-Allow-Origin',
                           value: '*', // Allow all origins
                       },
                       {
                           key: 'Access-Control-Allow-Methods',
                           value: 'GET, POST, PUT, DELETE, OPTIONS',
                       },
                       {
                           key: 'Access-Control-Allow-Headers',
                           value: 'Authorization, Content-Type',
                       },
                   ],
               },
           ];
       },
   };

在哪裡添加標頭的摘要:

  • Web 伺服器(Apache、Nginx):在伺服器設定檔中進行設定(例如 .htaccess、nginx.conf)。
  • 後端框架
    • Django:使用 django-cors-headers。
    • Go:手動新增標頭或使用 rs/cors 等中間件。
    • Node.js (Express):使用 cors 中介軟體。
  • 前端:在開發中,使用代理設定(如 React 的代理或 Next.js 自訂標頭)來避免 CORS 問題,但始終在生產中的後端處理 CORS。

以上是解決 CORS 問題的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn