解决vue的跨域问题:
1.创建一个新的文件命名为vue.config.js
2.编写解决跨域问题代码,配置跨域
module.exports = {
devServer: {
proxy: { //配置跨域
'/api': {
target: 'http://localhost:8081/', //这里后台的地址模拟的;应该填写真实的后台接口
changOrigin: true, //允许跨域
pathRewrite: {
/* 重写路径,当我们在浏览器中看到请求的地址为:http://localhost:8080/api/core/getData/userInfo 时
实际上访问的地址是:http://121.121.67.254:8185/core/getData/userInfo,因为重写了 /api
*/
'^/api': ''
}
},
}
}
}
和接口连接的代码:
methods: {
// getUser() {axios.get('http://localhost:8081/mybatis_plus/user/allUser').then(response => (this.tableData = response.data))}
getUser() {axios.get('/mybatis_plus/user/allUser').then(response => (this.tableData = response.data))}
},
created() {
this.getUser();
}
3.main.js里面导入axios
import axios from 'axios'
import Axios from 'axios'
Vue.prototype.$axios = Axios
Vue.config.productionTip = false
//跨域关键代码
Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api'
测试一下:
由图可以知道,我们浏览器请求的地址是前端是url,但是后台请求是我们后台接口的地址,这就解决了跨域的问题。