首先,我们要知道的是VUE中请求数据使用的 axios 组件, 所以,在请求数据时要先将 axios 组件引入, 跨域通过 npm install axios 或者使用 yarn add axios(使用yarn的前提是你已经安装了yarn)
npm install axios
在 main.js 中引入axios, 并在全局进行注册
import Axios from 'axios'
Vue.prototype.$axios = Axios
在congfig下的index.js中添加如下代码
proxyTable: {
"/api": {
target: "http://localhost:8081",// 要访问的接口域名
ws: true,// 是否启用websockets
changeOrigin: true, //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
pathRewrite: {
'^/api': '' //这里理解成用'/api'代替target里面的地址,比如我要调用'http://localhost:8081/user/add',直接写'/api/user/add'即可
}
}
},
最后一步就是使用了
this.$axios.get("/api/getUsers").then(res=>{
console.log(res)
})
}