*编辑 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