vue修改proxyTable解决跨域请求,报404的解决

环境:vue前端和后端接口部署在同一台机器。

vue服务部署在 http://localhost:8081,后台服务部署在 http://localhost:8080,可以看到端口是不一样的,在vue通过以下方式请求:

export default {
    name:'Condition',
    data(){
        return{
            options:[]
        }
    },
    created:function(){
        this.getdata();
    },
    methods:{
        getdata(){
            this.$axios({
                method:'get',
                url:'http://localhost:8080/college/getcollege'
                }).then(resp => {
                    this.options = resp.data.data.list;
                    console.log(resp.data);        
                }).catch(resp => {
                    console.log('请求失败:'+resp.status+','+resp.statusText);
                });
        }
    }
}

因为端口不一致,axios就会认为是跨域了,所以就会报错:

Access to XMLHttpRequest at 'http://localhost:8080/college/getcollege' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. [http://localhost:8081/#/]

这里只介绍通过修改config中的index.js文件中的proxyTable的配置去解决的方法。在网上随便搜一下,基本都是如下的内容:

        proxyTable: {
            "/api": {
                target: "http://localhost:8080",
                changeOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        },

修改后,绝大部分人都会遇到404的错误,如下:

the server responded with a status of 404 (Not Found) [http://localhost:8081/college/getcollege

奇怪吧,明明设置了代理,怎么没有生效呢?不是方法不对,而是没有理解proxyTable中节点的意义。其中的“api”节点,这是路由,系统会去根据这个匹配你的地址,匹配上才会生效,proxyTable中可以指定多个路由,一开始会认为这个是规定格式,所以都不会去修改,除非你的api部署地址是这样的“http://localhost:8080/api/*”,恭喜你,你的问题可能解决了,但是根据我的地址是“http://localhost:8080/college/getcollege”,就完蛋了,那么该怎么改,如下:

        proxyTable: {
    //碰到college路由就会起作用了
            "/college": {
                target: "http://localhost:8080",
                changeOrigin: true,
    //重定向,一般可以不用写,或者值写出空''
                pathRewrite: {
                    '^/college': '/college'
                }
            }
        },

OK,问题解决。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

bdmh

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

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

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

打赏作者

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

抵扣说明:

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

余额充值