预准备知识:跨域 CORS
后端配置允许所有源跨域、允许浏览器发送凭证(credentials):
@SpringBootApplication
public class SpringBootHelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHelloworldApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true);
}
};
}
}
CorsRegistry用于配置cors,默认配置是允许任何源访问、允许简单方法、允许所有头部、预请求结果持续30秒。
注意,CorsRegistry的允许所有源访问,是通过设置请求的Origin字段实现的,因此不会与allowCredentials冲突。
前端配置:
//开发环境配置--配置ajax
let baseUrl="http://localhost:8080"
$.ajaxSetup({
//ajax请求发送前预处理
beforeSend: function(xhr, options) {
//如果是根相对地址,则加上服务端前缀
if(options.url.startsWith("/")){
options.url=baseUrl+options.url;
}
//允许发送credentials
options.xhrFields=Object.assign(
options.xhrFields==null? {} : options.xhrFields,
{ withCredentials:true }
);
}
})
//现在可以跨域请求,前提是后端允许
$.get("/hello",function(data){
console.log(data);
})
这里前端配置复杂了点,简单的请看:跨域 CORS