vue-cli生成的项目,可在config/index.js中配置proxyTable实现跨域。
proxyTable详解
proxyTable: {
'/api': {
target: 'http://127.0.0.1:88',
changeOrigin: true,
pathRewrite: {
'^/api': '/api' // 重写路径
}
}
},
以上,前端地址http://localhost:8088,后端地址http://localhost:88,对含有/api前缀的接口进行代理
- '/api':匹配接口,并不是所有的请求都需要执行一下代理(如图片等)
- target:目标请求地址
- pathRewrite:重写路径,即匹配真实的后端接口(结合以下例子理解)
pathRewrite: {'^/api': '/api'},前端http://localhost:8088/api/imgList 匹配后端http://localhost:88/api/imgList
pathRewrite: {'^/api': ''},前端http://localhost:8088/api/imgList 匹配后端http://localhost:88/imgList
前端:
axios({
method: 'get',
url:'api/imgList',
}).then(function(res) {
console.log(res)
})
后端(django):
path('api/imgList', views.View.as_view())
# path('imgList', views.View.as_view()) 当 pathRewrite: {'^/api': ''}
proxyTable实现原理
浏览器禁止跨域,服务端并不禁止跨域。
vue项目运行时,会配置启动一个node服务,浏览器的请求发送到这个服务器,该服务启动一个http代理,将请求转到设置的目标服务器。
vue的proxyTable用的是http-proxy-middleware
参考:https://segmentfault.com/q/1010000014042635