*編輯1:錯誤似乎只與POST
請求有關
我有一個前端網站localhost
。上面有一個註冊頁面localhost/register
該網站呼叫後端函數來註冊用戶localhost:8080/api/register
我使用 Axios 來 POST 使用者名稱和密碼。瀏覽器發送兩個請求:OPTIONS 飛行前請求,然後是 POST 請求。
使用者建立成功,但是瀏覽器對 POST 請求拋出錯誤:
Reason: CORS header ‘Access-Control-Allow-Origin’ missing
事實上,它在對 POST 的回覆中缺失了。假設我的後端 cors 檔案配置正確,問題可能是由於我的 Docker + Nginx 設定的組合阻止了它或將標頭代理到錯誤的位置?
這是我的 nginx 設定:
server {
listen 8080;
index index.php index.html;
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
root /var/www/html/public;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
try_files $uri = 404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
server {
listen 80;
location / {
proxy_pass http://node:3000;
}
}
這是我的docker-compose.yml
:
networks:
mynetwork:
driver: bridge
services:
nginx:
image: nginx:stable-alpine
container_name: nginx
ports:
- "8080:8080"
- "80:80"
volumes:
- ./php:/var/www/html
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
depends_on:
- php
- node
networks:
- mynetwork
php:
build:
context: ./php
dockerfile: Dockerfile
container_name: php
user: "1000:1000"
volumes:
- ./php:/var/www/html
ports:
- "9000:9000"
networks:
- mynetwork
node:
build:
context: ./react
dockerfile: Dockerfile
container_name: next
volumes:
- ./react:/var/www/html
ports:
- "3000:3000"
networks:
- mynetwork
**編輯2:
後端是 Laravel,它有 CORS 中間件來處理它。事實上,它似乎確實有效,因為GET
請求OPTIONS
傳遞時沒有錯誤,只有POST
請求拋出此錯誤。
cors.php
這是Laravel 中的CORS 設定檔 ( ):
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['http://localhost'],
'allowed_origins_patterns' => ['*'],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true