问题描述:
由于使用前后端分离写网站,不可以避免的会使用 ajax 进行跨域请求,但发现两次请求都会创建两个 session ,无法达到将数据存入 session 实现数据共享的效果。
问题解决:
前端:最主要的是下面这行代码?:
xhrFields: {
withCredentials: true
}
$.ajax({
type: 'POST',
url: rootPath + '/manager/login',
dataType: 'JSON',
xhrFields: {
withCredentials: true
},
data: {
username: username,
password: password,
verifyCode: verifyCode
},
success: function(result) {
console.log(result)
},
error: function(error) {
console.log(error)
}
});
后端:最主要的是 setAllowCredentials(true);这行代码?:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CustomCORSConfiguration {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}