前端开发时,请求后台接口经常需要跨域,vue-cli实现跨域请求只需要打开config/index.js,修改如下内容即可。

//例如要请求的接口url为http://172.3.2.1:8000/look/1

module.exports = {
    dev:{
        proxyTable:{
            '/api':{
                target: 'http://172.3.2.1:8000',
                changeOrigin: true,
                pathRewrite: {
                  '^/api': ''
                }
            }
        }
    }
}

这时在你想请求接口的url处,输入/api/look/1 即可实现跨域请求。

这时如果打开F12会发现请求的url是localhost:8080/api/look/1,这其实是虚拟从本地请求数据,这样就不会有跨域的问题产生了。

一般情况下上面的方法是没有问题的,要是上面的方法行不通,可以试试这样写:

//例如要请求的接口url为http://172.3.2.1:8000/look/1

module.exports = {
    dev:{
        proxyTable:{
            '/look':{
                target: 'http://172.3.2.1:8000',
                changeOrigin: true,
                pathRewrite: {
                  '^/look': '/look'
                }
            }
        }
    }
}

这时在你想请求接口的url处,输入/look/1 即可实现跨域请求。

详情:https://vuejs-templates.github.io/webpack/proxy.html

Logo

前往低代码交流专区

更多推荐