【发布时间】:2020-02-14 20:01:44
【问题描述】:
我正在尝试使用在 Docker 中运行的 ReactJs 应用程序(不使用 express)发出 POST/PUT/PATCH/DELETE 请求,但我的请求被 CORS 阻止。我的后端是一个 Spring Boot Service,也在 Docker 中运行。
错误:
xhr.js:166 OPTIONS http://<MY_LOCAL_DOCKER_BACKEND_IP>:8080/api/... 403
和
Access to XMLHttpRequest at 'http://<MY_LOCAL_DOCKER_BACKEND_IP>/api/...' from origin 'http://<MY_LOCAL_DOCKER_FRONTEND_IP>:8090' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我也在使用 React-Router。
我在 nginx 上运行我的前端,这就是我的 nginx.conf 的样子:
server {
listen 8090;
server_name <MY_LOCAL_DOCKER_FRONTEND_IP>:8090;
access_log /var/log/nginx/host.access.log;
error_log /var/log/nginx/host.error.log;
root /usr/share/nginx/html;
index index.html index.htm;
location ~* \.(?:manifest|appcache|html?|xml|json)$ {
expires -1;
}
location ~* \.(?:css|js)$ {
try_files $uri =404;
expires 1y;
access_log off;
add_header Cache-Control "public";
}
# Any route containing a file extension (e.g. /devicesfile.js)
location ~ ^.+\..+$ {
try_files $uri =404;
}
location / {
root /usr/share/nginx/html;
index index.html;
autoindex on;
set $fallback_file /index.html;
if ($http_accept !~ text/html) {
set $fallback_file /null;
}
if ($uri ~ /$) {
set $fallback_file /null;
}
try_files $uri $fallback_file;
add_header 'Access-Control-Allow-Origin' 'http://<MY_LOCAL_DOCKER_FRONTEND_IP>:8090' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, PATCH, DELETE' always;
add_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type, Origin' always;
proxy_pass http://<MY_LOCAL_BACKEND_IP>:8080; #backend running on port 8080
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
注意:路由工作正常,只是我的主页下
http://<MY_LOCAL_DOCKER_FRONTEND_IP>:8090/
当我尝试直接打开它(通过 URL)时无法识别。路由到它(通过 NavBar)工作正常。
编辑:也许我的 Spring Config 是错误的?我正在使用这个适用于 GET 请求的全局示例。
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
【问题讨论】:
-
在您的 nginx 配置中,尝试为 OPTIONS 请求添加特定处理。在stackoverflow.com/a/55138166/441757查看答案
-
@sideshowbarker 感谢您的回答,我将其更改如下并将其添加到我当前的配置中。没有帮助我:(
($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin: $http_origin'); add_header 'Access-Control-Allow-Origin: GET, POST, , PUT, PATCH, OPTIONS'); add_header 'Access-Control-Allow-Credentials: true'); add_header 'Vary: Origin'); }
标签: reactjs nginx proxy react-router cors