Version: Next
解决跨域问题
CORS(Cross Origin Resourse-Sharing) 跨站资源共享
实际上先进行一次预检,来确定能否跨域访问
不能跨域访问,透过设置一系列的
头
来实现跨域
前端
配置一加载页面就发送Ajax请求,同时携带Token
window.onload = function () {
var headers = {};
headers['JWTHeaderName'] = "<这里替换为jwt令牌>";
$.ajax({
url: 'http://localhost:8081/hello',
type: "POST",
headers: headers,
success: function (data) {
alert("跨域请求配置成功")
},
error: function (data) {
alert("跨域请求配置失败")
}
});
}
配置类
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
...
}
}
- 设定跨域目标的站点地址
- 设置允许跨域的请求模式
- 设置允许跨域访问的路由地址
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:8888")); // 前端的部署地址,允许哪个URL的请求跨域访问我
configuration.setAllowedMethods(Arrays.asList("GET", "POST"));
configuration.applyPermitDefaultValues();
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}