跨域,是指浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的(CV)
关于浏览器为什么有同源策略这个东西,个人感觉水很深,大家感兴趣就自己去研究吧。
下面总结几种出现跨域情况:
▶ 不同域名
http://www.a.com/index.html 调用 http://www.b.com/server.do
▶ 同域名、不同端口
http://www.a.com:8080/index.html 调用 http://www.a.com:8081/server.do
▶ 同域名、不同协议
http://www.a.com/index.html 调用 https://www.a.com/server.do
▶ 主域名相同、不同子域名
http://www.a.com/index.html 调用 https://cn.a.com/server.do
SpringBoot解决跨域的三种方式
OPTION ONE:配置过滤器支持CORS(跨域资源共享)
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
@Component
public class CorsFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
OPTION TWO:配置addCorsMappings支持CORS(跨域资源共享)
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class SpringMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "DELETE")
.allowCredentials(true)
.allowedHeaders("*")
.maxAge(3600)
.allowedHeaders(
"Access-Control-Allow-Headers",
"access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
}
}
OPTION THREE:使用@CrossOrigin注解