解决前后端分离验证码获取不到及提交CORS 策略阻止的问题
问题:
-
提交获取不到验证码
-
下面的报错(可以提交,但报错)
Access to XMLHttpRequest at ‘http://localhost:8999/public/exchange/insert?n=cesium%E5%BC%80%E5%8F%91&s=cesium%E5%BC%80%E5%8F%91&c=3yx8’ from origin ‘http://localhost:63342’ has been blocked by CORS policy: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
-
前端ajax设置(前端ajax访问时要加上”xhrFields: {withCredentials: true}” ,实现session可以传递,验证码是根据session获取的)
url: base_url + “:” + port + “/public/exchange/insert”,
xhrFields: {
withCredentials: true
}, crossDomain: true,
-
后端配置SpringBoot
CorsConfiguration配置前面三个是跨域配置,setAllowCredentials是解决前端request’s credentials报错的问题
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); //允许任何域名
corsConfiguration.addAllowedHeader("*"); //允许任何头
corsConfiguration.addAllowedMethod("*"); //允许任何方法
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}