什么是浏览器跨域和springboot怎么解决
- 跨域:浏览器同源策略 1995年,同源政策由 Netscape 公司引⼊浏览器。⽬前,所有浏览器都实 ⾏这个政策。
最初,它的含义是指,A⽹⻚设置的 Cookie,B⽹⻚不能打开,除⾮这两个⽹⻚"同 源"。
所谓"同源"指的是"三个相同
协议相同 http https
域名相同 www.xdclass.net
端⼝相同 80 81
⼀句话:浏览器从⼀个域名的⽹⻚去请求另⼀个域名的资源时,域名、端⼝、协议任⼀不同,都是跨
域
浏览器控制台跨域提示:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
- 解决⽅法
1)JSONP
2)Http响应头配置允许跨域
nginx层配置 参考:https://www.cnblogs.com/hawk-whu/p/6725699.html
3)程序代码中处理 SpringBoot 通过拦截器配置
主要讲解SpringBoot配置:
1、使用@CrossOrigin 注解实现
#如果想要对某一接口配置 CORS,可以在方法上添加 @CrossOrigin 注解 :
@CrossOrigin(origins = {"http://IP地址:端口号", "null"})
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String greetings() {
return "{\"project\":\"just a test\"}";
}
#如果想对一系列接口添加 CORS 配置,可以在类上添加注解,对该类声明所有接口都有效:
@CrossOrigin(origins = {"http://IP地址:端口号", "null"})
@RestController
@SpringBootApplication
public class SpringBootCorsTestApplication {
}
#如果想添加全局配置,则需要添加一个配置类 :
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}
#或者通过拦截器配置
public class CorsInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//表示接受任意域名的请求,也可以指定域名
response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
//该字段可选,是个布尔值,表示是否可以携带cookie
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "*");
//这里可以不加,但是其他语言开发的话记得处理options请求
/**
* 非简单请求是对那种对服务器有特殊要求的请求,
* 比如请求方式是PUT或者DELETE,或者Content-Type字段类型是application/json。
* 都会在正式通信之前,增加一次HTTP请求,称之为预检。浏览器会先询问服务器,当前网页所在域名是否在服务器的许可名单之中,
* 服务器允许之后,浏览器会发出正式的XMLHttpRequest请求
*/
if(HttpMethod.OPTIONS.toString().equals(request.getMethod())){
return true;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}