在Web开发中,当浏览器发起跨域请求时,会先发送一个OPTIONS方法的预检请求(preflight),确认服务器是否允许实际请求。这会导致每个跨域请求实际上发送两次请求。
在Nginx配置中添加以下内容来处理跨域请求:
server {
listen 80;
server_name yourdomain.com;
location / {
# 处理Vue单页面应用的路由问题
try_files $uri $uri/ /index.html;
}
location /api/ {
# 允许跨域请求
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
# 处理OPTIONS预检请求
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;
}
# 反向代理到实际API服务器
proxy_pass http://api_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;
}
}
在Vue Router中启用history模式:
const router = new VueRouter({
mode: 'history',
routes: [...]
})
如果可能,替换通配符*
为具体的允许域名:
add_header 'Access-Control-Allow-Origin' 'https://your-frontend-domain.com';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Max-Age' 86400; # 缓存预检请求结果24小时
add_header 'Access-Control-Allow-Credentials' 'true';
注意:当使用凭证时,Access-Control-Allow-Origin
不能设置为*
。
# 对于简单GET请求,不需要预检
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET';
add_header 'Access-Control-Allow-Headers' 'Content-Type';
}
try_files $uri $uri/ /index.html
Access-Control-Allow-Credentials
并指定具体域名而非*
Access-Control-Max-Age
减少预检请求通过以上配置,可以有效解决WebAPI跨域二次请求问题,并确保Vue单页面应用的路由正常工作。