## 安裝axios 和 qs
qs :qs是一個庫。里面的stringify方法可以將一個json對象直接轉為以?和&符連接的形式 自動化數據
> 安裝qs ` npm install qs`
> 安裝axios `npm i --save axios`
## 在mian.js中引入axios
```
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
import qs from 'qs'
Vue.config.productionTip = false
Vue.prototype.axios = axios
Vue.prototype.qs = qs
//默認后臺接口前綴
// axios.defaults.baseURL = 'http://10.10.10.114:8073'
//不填默認接口前綴為本地ip
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
```
## 使用axios請求接口數據
```
this.axios.post("applet/selBanner", this.qs.stringify(param)).then(res => {
console.log(res);
});
```
## 跨域
在文件vue.config.js 中配置代理
```
devServer: {
// host: 'localhost',
// port: 8020,
// https: false,
// hotOnly: false,
// open: true,
"disableHostCheck":true,
proxy: {
'/api': {
target: 'http://10.10.10.114:8073', //跨域地址
changeOrigin: true,
pathRewrite: {
'^/api': '/'
}
}
}
},
```
在文件mian.js中設置baseURL
```
axios.defaults.baseURL = '/api/'
```
### 跨域請求思路
> 實際顯示請求為 本地地址 + /api/ + 接口 http://10.10.10.108:8080/api/applet/selBanner
> 事實上 http://10.10.10.108:8080/api 被解析成了配置的target地址 http://10.10.10.114:8073
> 真正上請求地址為 http://10.10.10.114:8073/applet/selBanner