1.CorsConfig工具类(可选可不选)
package com.ruoyi.framework.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author: Cheng Rong yu
* @Description: 解决跨域问题
* @date: 2022-08-08
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry){
//设置允许跨域的路径
registry.addMapping ("/**")
//设置允许跨域请求的域名
.allowedOriginPatterns ("*")
//是否允许证书
.allowCredentials (true)
//设置允许的方法
.allowedMethods ("GET","POST")
//设置允许的header属性
.allowedHeaders ("*")
//允许跨域时间
.maxAge (3600);
}
}
2.在需要跨域的controller类上添加注解:@CrossOrigin
(必写)
3.vue,config.js
加入如下代码
devServer: {
proxy: {
//名字可以自定义,这里我用的是api
'/api': {
target: process.env.VUE_APP_API_BASE_URL,//设置你调用的接口域名和端口号(目标IP:端口)
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
或者使用nginx配置
location ^~ /api {
proxy_pass http://xxx:xx/;
}
需要跨域导出blob文件的,需要使用axios
的get
请求传参
调用axios
方法前
/**
* 调用axios时前端加上默认路由/api 实现跨域
*/
this.axios.defaults.baseURL = '/api';
this.axios({
method: "get",
url: "xxx",
responseType: 'blob' // 设置响应结果类型为blob类型
}).then(res => {
// 处理数据,并下载
const blob = new Blob([res.data]);
let url = window.URL.createObjectURL(blob)
let link = document.createElement('a')
link.href = url
link.setAttribute('download', 'test.csv')
document.body.appendChild(link)
link.click()
})
}
或者在main.js
中默认写死axios.defaults.baseURL = '/api';
4.完工,回家睡觉🤣