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,问题解决。

发布了130 篇原创文章 · 获赞 42 · 访问量 79万+

猜你喜欢

转载自blog.csdn.net/bdmh/article/details/102739039