1、项目中遇到的问题描述:
前端调用zuul统一网关服务接口,请求状态码200,但是无返回数据。
浏览器控制台报错信息:No Access-Control-Allow-Origin header is present on requested resource .
2、解决问题
借鉴https://blog.csdn.net/envon123/article/details/83270277博客。
项目配置如下:
location /xxxx-server { #/xxxx-server不能以/结尾
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
#springcloud的zuul组件对外统一网关,xxxx-server是springcloud的后台服务组件
proxy_pass http://127.0.0.1/xxxx-server; #/xxxx-server不能以/结尾
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}