其他分享
首页 > 其他分享> > Vue解决跨越问题

Vue解决跨越问题

作者:互联网

Vue解决跨越问题:has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’

在根目录vue.config.js(没有则手动创建一个)添加如下代码:

module.exports = {
    devServer: {
        proxy: {
            '/api': {
                target: 'http://localhost:8090',//服务端URL
                changeOrigin: true,
                pathRewrite: {                   //路径重写
                    '^/api': ''                     //选择忽略拦截器里面的单词
                },
            },
        }
    }
}

这里/api的意义是为了防止前后端路径相同导致冲突,所以还需要在所有URI中加上/api,同时如果有其他不同的服务端还可以这样区分:

module.exports = {
    devServer: {
        proxy: {
            '/api': {
                target: 'http://localhost:8090', 
                changeOrigin: true,
                pathRewrite: {                   
                    '^/api': ''                     
                },
            },
            '/otherApi': {
                target: 'http://localhost:9090',
                changeOrigin: true,
                pathRewrite: {                   
                    '^/otherApi': ''               
                },
            },
        }
    }
}

最后,一定要重启npm!


*补充:上面方法只适合开发环境,当Vue项目打包成静态文件时,他的代理也就失灵了,因为代理的前提是本地必须有service

标签:Vue,target,pathRewrite,跨越,changeOrigin,api,解决,true,localhost
来源: https://blog.csdn.net/monk0271_chen/article/details/120356319