vue2.6.11 版本解决跨域

本文介绍如何在Vue项目中配置跨域,通过设置vue.config.js实现开发环境下的跨域代理,并提供部署后的解决方案及后端配置示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发时候 新建 vue.config.js文件,位置如下:在这里插入图片描述
内容如下:

module.exports = {
    devServer: {
        open: true,
        host: 'localhost',
        port: 8080,
        https: false,
        //以上的ip和端口是我们本机的;下面为需要跨域的
        proxy: { //配置跨域
            '/shiro': {  // 这里和方法里 axios里的 url匹配   (本行为第9行)
                target: 'http://localhost:9090/shiro/', //这里后台的地址模拟的;应该填写你们真实的后台接口  // 这里和后台地址完全匹配
                ws: true,
                changOrigin: true, //允许跨域
                pathRewrite: {
                    '^/shiro': '' //请求的时候使用这个api就可以 // 这里和  第9行匹配
                }
            }
        }
    },
    configureWebpack: {

        performance: {
            hints: 'warning',
            //入口起点的最大体积
            maxEntrypointSize: 50000000,
            //生成文件的最大体积
            maxAssetSize: 30000000,
            //只给出 js 文件的性能提示
            assetFilter: function(assetFilename) {
                return assetFilename.endsWith('.js');
            }
        }
    },
    publicPath: './',

}


注意: proxy: {}
在这里插入图片描述
在这里插入图片描述

但是,这样有缺点,这样只能在开发时使用。在开发时,这样调用后台接口即可


      this.$axios({
        method: "post",
        url: "/shiro/sys/login",
        data: {
          username: this.username,
          password: this.password
        }
      }).then(result => {})

但是项目部署后,就会出现地址找不到。
所以,把上面的代码改为这样即可:

   this.$axios({
        method: "post",
        url: "http://localhost:9090/shiro/sys/login",
        data: {
          username: this.username,
          password: this.password
        }
      }).then(result => {})

不过这样做之后,在后端就得要加个配置类了。新建 WebMvcConfiguration类,写上如下内容:

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
//        registry.addMapping("**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET","PUT", "DELETE")
                .allowCredentials(true)
                .allowedHeaders("*")
                .maxAge(3600);
    }
}

即可解决跨域问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值