喵星之旅-狂奔的兔子-vue跨域解决

一、安装axios

(可以参考http://www.axios-js.com/docs/vue-axios.html)

在项目中执行

1
npm install --save axios vue-axios

二、在main.js中添加

1
2
3
4
5
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

三、修改配置文件

位于项目根路径下的vue.config.js,与src同级,如果没有则添加。

添加如下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
module.exports = {
devServer: {
//以上的ip和端口是我们本机的;下面为需要跨域的
proxy: {//配置跨域
'/api': {
target: 'http://127.0.0.1:8111/',//这里后台的地址模拟的;应该填写你们真实的后台接口
ws: true,
changOrigin: true,//允许跨域
pathRewrite: {
'^/api': ''//请求的时候使用这个api就可以
}
}

}
}
}

四、方法中使用

(可以参考http://www.axios-js.com/docs/vue-axios.html)

1
2
3
4
5
this.axios.get("/api/test/hello").then((response) => {
this.menuList = response.data;

})

这里面访问的真实地址就是 http://127.0.0.1:8111/test/hello

或者post请求:

1
2
3
4
5
6
this.axios.post(`/api/test/login`,"username=" + this.loginForm.username + "&password=" + this.loginForm.password)
.then(res=>{
console.log('res=>',res);
console.log(res.data);

})
文章目录
  1. 一、安装axios
  2. 二、在main.js中添加
  3. 三、修改配置文件
  4. 四、方法中使用
|