前后端分离,spring boot跨域问题
- - 编程语言 - ITeye博客1995年,同源政策由 Netscape 公司引入浏览器. 目前,所有浏览器都实行这个政策. 最初,它的含义是指,A网页设置的 Cookie,B网页不能打开,除非这两个网页"同源". 所谓"同源"指的是"三个相同". 协议相同/域名相同/端口相同. 一句话:浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域.
server{
listen 8099;
server_name wdm.test.cn;
location / {
// 没有配置OPTIONS的话,浏览器如果是自动识别协议(http or https),那么浏览器的自动OPTIONS请求会返回不能跨域
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "$http_origin";
add_header Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, DELETE";
add_header Access-Control-Max-Age "3600";
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization";
add_header Access-Control-Allow-Credentials "true";
add_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}
add_header 'Access-Control-Allow-Origin' '$http_origin';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, PUT, POST, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type,*';
proxy_pass http://127.0.0.1:8080;
}
}
第二步:程序代码中处理@Configuration
public class Cors extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
.allowCredentials(true).maxAge(3600);
}
}
如果想做到更细致也可以使用@CrossOrigin这个注解在controller类中使用。@CrossOrigin(origins = "http://192.168.1.97:8080", maxAge = 3600)
@RequestMapping("rest_index")
@RestController
public class IndexController{}
(注意点:假如接口报错,则跨域配置不生效)