前几讲咱们创建了前端和后端两个项目的基础框架,前端和后端项目如何联动起来呢,前端项目提供UI展示,后端服务提供数据支撑,前后两端通过rest接口来进行交互。
一、前端项目 1、整合axiosaxios时目前最流行的ajax封装库之一,用于很方便地实现ajax请求的发送。
添加依赖npm install axios测试
我们使用之前的test.vue页面和SpringBoot后台的测试接口做测试。
test.vue文件
主要按钮
点击测试按钮会发现浏览器控制台报错了
这是跨域问题引起的,因为我们浏览器访问的是9081端口,而访问后台的端口是8888端口,而且部署到服务器以后可能不光两者端口不同,连ip可能都会不同了。这就是跨域问题。
二、后端SpringBoot跨域支持package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600);
}
}
重启后端服务,测试点击按钮发现成功返回后端数据。



