什么是跨域?
由于浏览器的同源策略,一个域下的文档或脚本试图去请求另一个域下的资源,就会产生跨域,那么怎么才算同源呢,即满足 协议相同、端口相同、主机相同。
跨域常见情景
跨域常见错误
Access to XMLHttpRequest at 'xxx' from origin 'xxx' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
Nginx跨域配置
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE' always;
add_header 'Access-Control-Allow-Headers' '*' always;
add_header 'Access-Control-Max-Age' 1728000 always;
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain; charset=utf-8';
return 204;
}
if ($request_method ~* '(GET|POST|DELETE|PUT)') {
add_header 'Access-Control-Allow-Origin' '*' always;
}
}
扩展
因在开发中的请求路径需要重写规则,导致访问地址出现404,故记录一下。
location /api/intefaces {
proxy_pass http://127.0.0.1:8080;
proxy_connect_timeout 600;
proxy_read_timeout 600;
rewrite "^/api/(.*)$" /$1 break;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_connect_timeout 600;
proxy_read_timeout 600;
}
解释:
proxy_pass:反向代理,不赘述。
rewrite:路径重写。
^/api/(.*)$ :正则,表示api之后的路径进行分组,/$1 即取组1进行路径重写
break:重写后不在重新匹配
总结
以上配置虽然解决了跨域,但是并不安全,因为放开了所有请求,实际配置要根据线上环境进行配置,如大家有其他更好的方案或者意见环境讨论。