VUE網路請求中的axios
阿新 • • 發佈:2018-12-06
- 安裝依賴
npm install axios --save
- 引入到 main.js 中
import axios from 'axios'
- 載入到 Vue 的原型上,讓整個 Vue 可以使用
Vue.prototype.$axios = axios
- 有可能跨域,這時就要設定代理
在 config 下的 index.js 檔案中新增
proxyTable: { '/api':{ target:'跨域地址', changeOrigin:true, pathRewrite:{ '^/api':'' } }, }
在 config 下的dev.env.js 檔案中新增
API_HOST:'"/api"'
在 config 下的 prod.env.js 檔案中新增
API_HOST:'"線上的地址"'
這樣請求時的 url 就是:
url: process.env.API_HOST + ''
- get 請求
this.$axios({ method: 'get', url: process.env.API_HOST + '', params:{}, }) .then(data => { console.log(data); }).catch(err => { console.log(err) });
- post請求
import Qs from 'qs';
this.$axios({
method: 'post',
url: process.env.API_HOST + '',
data: {},
transformRequest: [(data) => {
data = Qs.stringify(data);
return data;
}],
}).then(data => {});
- 如果傳值規定為JSON,那麼將
transformRequest: [(data) => { data = Qs.stringify(data); return data; }],
改為:
dateType: JSON,
- 為了傳固定的cookie,在 main.js 中新增
axios.defaults.withCredentials = true;
- 在 main.js 中配置攔截:
// 新增請求攔截器
axios.interceptors.request.use(config => {
// 在傳送請求之前做些什麼
return config;
}, error => {
// 對請求錯誤做些什麼
return Promise.reject(error);
});
// 新增響應攔截器
axios.interceptors.response.use((response) => {
// 對響應資料做點什麼
return response;
}, (error) => {
// 對響應錯誤做點什麼
return Promise.reject(error);
});