跨域配置
何为跨域
跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对 JavaScript 施加的安全限制。 所谓同源是指,域名,协议,端口均相同,举个栗子:
http://www.123.com/index.html
调用 http://www.123.com/server.json
(非跨域)
http://www.123.com/index.html
调用 http://www.456.com/server.json
(主域名不同:123/456,跨域)
http://abc.123.com/index.html
调用 http://def.123.com/server.json
(子域名不同:abc/def,跨域)
http://www.123.com:8080/index.html
调用 http://www.123.com:8081/server.json
(端口不同:8080/8081,跨域)
http://www.123.com/index.html
调用 https://www.123.com/server.json
(协议不同:http/https,跨域)
请注意:localhost 和 127.0.0.1 虽然都指向本机,但也属于跨域。
如何解决
SpringBoot Cors 配置
java
//springboot可以直接配置到自带的`addCorsMappings`方法内
@Configuration
public class CbbConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("*")
.maxAge(3600)
.allowCredentials(true);
}
}
Nginx 配置(推荐)
核心思想就是通过 nginx 或者其他反代工具,将本是跨域的接口地址代理到本地,再调用本地代理后的地址,即可解决跨域问题。
shell
server {
listen 80;
server_name localhost;
root /usr/share/nginx/cbb;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
location /server{
proxy_pass http://xxx.com;
add_header Cache-Control no-store;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
总结
- Nginx 配置反代的模式,虽然看上去麻烦,需要每个地方都配置跨域,但是由于 nginx 的高性能,将 API 反向代理后,并不会有明显的损耗,同时也变相降低了服务端的压力。所以推荐使用 Nginx 或其他反代工具来解决跨域问题。