开发中肯定是避免不了跨域问题的,这里说的是开发环境中的配置,如果是生产环境需要nginx代理或者cors。
vue-cli 2.x配置
配置文件在config/index.js
proxyTable: {
// 匹配开头为 /api
'^/api':{
// 跨域的域名
target: 'http://localhost:3000',
changeOrigin:true,
pathRewrite:{ // 路径重写
// 请求/api/user 会被重写为/fetch/user
'^/api': '/fetch'
}
}
}
axios请求数据
// 指向 => http://localhost:3000/api/user
axios.get('/api/user')
.then(res => {
// do something...
})
.catch(e => e)
多个条件匹配
proxyTable: {
'/api':{
target: 'http://localhost:3000',
changeOrigin:true
},
'/test':{
target: 'http://localhost:3000',
changeOrigin:true
},
// 如果请求的图片地址是相对路径也可以配置代理
'/images':{
target: 'http://localhost:3000',
changeOrigin:true
}
}
vue-cli 3.x配置
项目根目录编辑vue.config.js,如果没有就新建
module.exports = {
devServer: {
proxy: {
'/api':{
target: 'http://localhost:3000',
changeOrigin:true
},
'/test':{
target: 'http://localhost:3000',
changeOrigin:true
},
// 如果请求的图片地址是相对路径也可以配置代理
'/images':{
target: 'http://localhost:3000',
changeOrigin:true
}
}
}
}
vue-cli代理底层使用的是http-proxy-middleware,更详细的配置可以参考这里 http-proxy-middleware