前言:自己按照网上的教程鼓捣了两天才鼓捣明白 故写此文章记录
此教程跟网上的大多数前后端分离跨域文章不一样 请看到最后
一、前端部分
1、首先安装axios
npm install --save axios
2、封装工具类 在src目录下中新建文件utils 在utils文件夹中创建request.js文件 引入 axios 其中 QS是aios库中带的
//直接引入
import axios from 'axios'
//因为axios默认发的是json格式数据,我们要做表单提交,需要更改axios配置
// 引入 Qs是为了把json格式,转为formdata 的数据格式
import Qs from 'qs'
const service = axios.create({
baseURL: 'http://localhost:8088',
timeout: 1000,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: [function (data) {
// 对 data 进行任意转换处理
return Qs.stringify(data);
}],
});
export default service;
截图
3、在 min.js 中添加 request 工具类
import http from '@/utils/request'
Vue.prototype.http=http
截图
4、在页面中引入接口 比如在登录页面login.vue引入 接口
this.http({
method: 'post',
url: '/login',
data: this.user
}).then(res => {
alert(res.data.msg)
if (res.data.msg === 200) {
this.$router.replace('Home')
}
})
二、后端部分
1、添加配置类 Config
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;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.time.Duration;
/**
* @description:
* @author:
* @created: 2021/03/12 16:16
*/
@Configuration
public class Config implements WebMvcConfigurer {
public CorsConfiguration buildConfig(){
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*"); //允许任何域名
config.addAllowedHeader("*"); //允许任何头
config.addAllowedMethod("*"); //允许任何方法
config.addAllowedOrigin("*");
config.setMaxAge(Duration.ofDays(30)); //设置30天之内不在发送OPTIONS预请求
return config;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
或者采用以下写法:
@Configuration
public class Config implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
2、配置 spring security 在WebSecurityConfig类 configure方法中添加 http.cors();
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}
到这里就写完了