通过nginx 解决跨域问题
跨域问题:后端是spring cloud的分布式服务,前端vue调用,部署测试环境,调用不同服务的时候,报错, 跨域请求被浏览器阻止
1,下载nginx的包
2,进入conf文件目录修改nginx.conf文件,改为如下格式。
worker_processes 1;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;# 定义 CORS 配置为一个变量,避免重复map $http_origin $cors_origin {default "*";}server {listen 端口;server_name ip;# 统一的 CORS 配置add_header Access-Control-Allow-Origin "$cors_origin" always;add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization" always;add_header Access-Control-Allow-Credentials "true" always;add_header Access-Control-Max-Age 86400 always;# 处理 OPTIONS 请求if ($request_method = 'OPTIONS') {return 204;}# 优先处理接口请求location /开头/ {proxy_pass http://xxxxx-ip:端口/;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;# 调试信息add_header X-Proxy-Path $request_uri always;add_header X-Proxy-Host $host always;# 详细日志access_log xxxxxx}# 处理静态资源location / {root xxx前端位置}}
}