这些天使用了vue和springboot尝试了一下完全分离的开发方式,在vue中使用ajax请求,如果前后端都在同一台电脑上,ajax是无法处理不同端口的请求的。例如前端的端口是8080,而后端端口是80,那么就访问不到。
同时如果前端多次提交ajax请求,后端每次接收到的session也不同,是因为ajax提交请求的时候不带服务器的信息,导致后端以为是不同的用户发出的请求。
网上尝试了很多种方法,最后解决方法是这样的,可能有错误,只算记录吧,大家有需要可以参考一下:
1、在vue中对ajax进行设置,使其携带浏览器信息进行传递。
axios.defaults.withCredentials = true;
2、在springboot中的controller中加入注解
//设置允许跨域访问
@CrossOrigin
public class xxxController {}
3、新建MPconfig文件。
@Configuration
public class MPConfig implements WebMvcConfigurer {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("http://localhost:8081"); // 允许任何域名使用
corsConfiguration.addAllowedOrigin("http://localhost:8080"); // 允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 允许任何头
corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
return corsConfiguration;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedHeaders("*")
.allowedMethods("*")
.maxAge(1800)
.allowedOrigins("http://localhost:8081");
}
}