vue代理
使用vue時,經常遇到使用npm run serve
后,與后端出現跨域問題,獲取不到數據,其中一個解決方法,就是在前端,vue中開啟代理proxy。
vue.config.js文件:
module.exports = {
devServer: {
proxy: {
'/': {
target: 'https://demo.com',
secure: true,
changeOrigin: true
},
'/api/': {
target: 'http://test.com', // 接口路徑
ws: true, // 如果要代理websockets,配置該參數
secure: false, // 如果接口為https,需要配置該參數
changeOrigin: true, // 是否跨域
pathRewrite: { // 改寫接口請求地址,把/api改為/
'^/api': '/'
}
}
}
}
}
配置后,請求地址會出現對應的變化:
原本的配置請求:
axios.get('https://demo.com/v0/find')
axios.get('http://test.com/v1/user/find')
配置后的配置請求:
axios.get('/v0/find')
axios.get('/api/v1/user/find')