Vue配置代理
1.安装axios
npm install axios
2.找到 vue.config.js
module.exports = {
transpileDependencies: true,
lintOnSave: false, //关闭语法检查
//开启代理服务器(方式一)
// 5000是后台的端口
// devServer: {
// proxy: "http://localhost:5000",
// },
//开启代理服务器(方式二)
// api:前缀 调用接口时:http://localhost:8080/api/...
devServer: {
proxy: {
"/api": {
target: "http://localhost:5000",
pathRewrite:{'^/api':''}, //请求后台时忽略前缀 重要!!!
// vue中默认开启 ws changeOrigin
ws: true, //用于支持websocket
changeOrigin: true,//用于控制请求头中的host值
},
//多个代理
"/foo": {
target: "http://localhost:5001",
pathRewrite:{'^/foo':''},
},
},
},
};
3.页面调用
<script>
import axios from 'axios'
export default {
data() { },
methods: {
geData() {
axios.get('http://localhost:8080/api/data').then(
response => {
console.log('请求成功了', response.data)
},
error => {
console.log('请求失败了', error.message)
}
)
}
},
}
</script>