跨域问题解决(后端Java+前端Vue2)

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文件的,需要使用axiosget请求传参
调用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.完工,回家睡觉🤣

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程似锦吖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值