axios从安装到使用的教程
安装axios:npm install --save axios目录结构:红框部分是接口文件:appApi.js是存放接口的文件import Vue from 'vue'import axios from 'axios'export default {// 获取分类show_category: function () {retur...
·
安装axios:
npm install --save axios
目录结构:
红框部分是接口文件:
appApi.js是存放接口的文件
import Vue from 'vue'
import axios from 'axios'
export default {
// 获取分类
show_category: function () {
return axios.post('/point-api-show_category');
},
// 获取商品
get_product: function (data) {
return axios.post('/point-api-get_product',data);
}
}
apiServer.js是设置vue的属性API的:
import Vue from 'vue'
import API from './API/appApi'
Vue.prototype.API = API;
在main.js里引入axios和apiServer.js
import ProtoTypeAPI from './network/apiServer'
import axios from 'axios'
new Vue({
el: '#app',
router,
store,
axios,
template: '<App/>',
components: { App },
methods: {
setSessionStorage:function(data) {
for(let key in data){
sessionStorage[key] = data[key];
}
},
setLocalStorage: function(data) {
for(let key in data){
localStorage[key] = data[key];
}
}
}
})
组件里调用接口:
get_product: function (name,cate_id) {
this.API.get_product({
name: name,
cate_id: cate_id
}).then((response) => {
console.dir(response);
}, (response) => {
mui.toast('网络错误');
});
}
设置拦截器header.js文件,引入了config.js配置文件:
import Vue from 'vue'
import axios from 'axios'
import GLOBAL_CONFIG from './config'
// 设置默认的配置项
const CONFIG = GLOBAL_CONFIG['GLOBAL_CONFIG'];
axios.defaults.baseURL = CONFIG['API_HOST'];
//添加请求拦截器
axios.interceptors.request.use(function(config){
// 获取token
let TOKEN=localStorage.token;
// 设置token
if(TOKEN){
config.headers['X-ODAPI-Authorization'] = TOKEN;
}
// 返回配置项
return config;
},function(error){
//请求错误时做些事
return Promise.reject(error);
});
//添加响应拦截器
axios.interceptors.response.use(function(response){
// console.log(JSON.stringify(response));
if(response['status'] == 200){
if(response['data']['error_code'] == 0){
return response['data']['data'];
}else{
if(response['data'].hasOwnProperty('erron')){
mui.toast(response['data']['erron']);
}
return false;
}
}else{
mui.toast('网络错误!');
}
},function(error){
//请求错误时做些事
return Promise.reject(error);
})
配置文件config.js
export default {
GLOBAL_CONFIG :{
'API_HOST': '接口地址',
'base64Header': 'data:image/png;base64,',
'dataImage':'data:image',
'db':'odoo3',
}
}
更多推荐
已为社区贡献11条内容
所有评论(0)