正是标题所说的,但为了上下文:
我确实可以访问上游资源,并且我允许那里的所有来源。
当我的 NGINX conf 不包含add_header 'Access-Control-Allow-Origin' '*';
我的浏览器告诉我的指令时:
从源“http://localhost:8080”访问“http://localhost/{{ upstream_path_redacted }}”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问” -Control-Allow-Origin' 标头存在于请求的资源上。
当我确实包含上述指令时,我的浏览器会告诉我
从源“http://localhost:8080”访问“http://localhost/{{ upstream_path_redacted }}”处的 XMLHttpRequest 已被 CORS 策略阻止:“Access-Control-Allow-Origin”标头包含多个值“ http://localhost:8080, *',但只允许一个。
第二个问题是有道理的。正如我所说,我允许上游服务器上的所有来源。因此,我不明白为什么删除指令会导致第一个问题。
我的nginx.conf
:
events {}
http {
upstream my-upstream-service {
server my-upstream-service:5000;
}
server {
listen 80 default_server;
location / {
# this works fine. just included as base case.
return 200 'ok';
add_header Content-Type text/plain;
add_header 'Access-Control-Allow-Origin' '*';
}
location /upstream {
# removing the next uncommented line results in 'missing header' issue.
# keeping it results in 'multiple header' issue.
add_header 'Access-Control-Allow-Origin' '*';
proxy_pass http://my-upstream-service;
}
}
}
更让我困惑的是:在查看 和 日志my-upstream-server
的nginx
日志后,请求已成功发送到上游服务器???
我所有的挖掘都让我找到了解决上述任何一个问题的解决方案,但不是当这两个问题都发生时该怎么办。我难住了。
如有必要,进一步的上下文:我docker-compose
用来部署这些服务(包括前端,它是一个 Vue SPA)。
这my-upstream-service
是一个Flask
使用 Flask-Cors 的网络服务器。
这是docker-compose.yml
---
version: '3.8'
networks:
gateway-service:
driver: bridge
services:
my-upstream-service:
build:
context: path/to/context/
dockerfile: path/to/dockerfile
ports:
- "5000:5000"
expose:
- "5000"
networks:
- gateway-service
frontend:
build:
context: /path/to/context
dockerfile: /path/to/dockerfile
ports:
- "8080:8080"
expose:
- "8080"
depends_on:
- gateway
networks:
- gateway-service
gateway:
image: nginx:1.19.8-alpine
volumes:
# this is where my nginx.conf lives.
- ./nginx/:/etc/nginx/
ports:
- "80:80"
environment:
- NGINX_PORT=80
depends_on:
- my-upstream-service
networks:
- gateway-service