SpringBoot + JQuery 解决 CORS跨域

CORS跨域分为后端和前端两个步骤

后端解决

实现WebMvcConfigur

@Configuration
public class WebConfig implements WebMvcConfigurer {

}

重写addCorsMappings

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("*")
                .allowedMethods(new String[]{"GET","PUT","POST","DELETE"})
                .allowedHeaders("*")
                .exposedHeaders("*")
                .maxAge(3600);
    }
}

前端解决

临时解决

$.ajax({
            type: "get",
            async: true,
            url: "http://localhost/sign",
            xhrFields: {
                withCredentials: true
            },
            success:function (o){
                console.log(o)
            }
        });

全局解决

//设置全局有效
$.ajaxSetup({
    xhrFields: {
        withCredentials: true
    }
})
//普通get
$.get("http://localhost/accept",function (o) {
            console.log("P1:"+o)
        });

上一篇:jQuery基础使用


下一篇:beego orm 一对多、多对多 关联查询