# SpringBoot+vue 前后端对接,解决跨域问题。

1 启动 vue 项目

打开终端到 vue 项目工程的目录下执行命令

npm run serve

2 打开 SpringBoot 项目,配置跨域 Config 类

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SuppressWarnings("all")
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    // 解决跨域问题
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOriginPatterns("*")
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
                .allowCredentials(true).maxAge(3600).allowedHeaders("*");
    }
}

3 启动 SpringBoot 项目请求一下 Controller 路径,查看是否有问题

image-20230420155511006

4 没问题后在 vue 项目中填写如下代码来获取 SpringBoot 请求路径响应的 Json 数据

created(){
  const _this = this							//then: 回调
  axios.get('http://localhost/user/all').then(function(resp){
      for(let i = 0,end = resp.data.data.length;i < end;i ++){
          _this.studentId = resp.data.data[i].studentNumber
          _this.Athome = resp.data.data[i].name
      }
      console.log(resp.data.data[0].name);
     	console.log(resp);
    });
}

跨域失败情况

  • 如果跨域失败 SpringBoot 启动访问路径可能会报错 500
  • 下面是跨域不成功访问 vue 项目所报的错

image-20230420160350631

跨域成功情况

  • 跨域成功请求 vue 项目所相应的数据

image-20230420160620159