• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
小码哥-倩倩
博客园    首页    新随笔    联系   管理    订阅  订阅

vue项目封装方法

封装网络请求,以及错误处理
import Vue from 'vue'
import axios from 'axios'
//错误处理
const errorCode =[
'400','401',
];
const errorInfoArray = [
{code:'200',title:'网络请求成功',info:'网络请求已成功'},
{code:'400',title:'请求失败',info:'登录设备类型错误'}
];
//错误处理
let isErrorCode = function(code){
for(var i=0;i<errorCode.length;i++){
if( errorCode[i] == code ){
return true;
}
}
return false;
};
let errorTitle = function(code){
for(var i=0;i<errorInfoArray.length;i++){
if( errorInfoArray[i].code == code ){
return errorInfoArray[i].title;
}
}
};
let errorInfo = function(code){
for(var i=0;i<errorInfoArray.length;i++){
if( errorInfoArray[i].code == code ){
return errorInfoArray[i].info;
}
}
};

//默认配置
axios.default.timeout = 6000;
axios.default.responseType = 'json'
//axios.default.baseURL = "http://test.wulian.81dd.cn"//不起作用
axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';

axios.interceptors.request.use(function (config) {
// 发送请求之前做些什么
config.headers.token = sessionStorage.getItem("token");//请求头
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
console.log('相应数据',response);
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
Vue.prototype.$http = function(url,data){
let promise = new Promise((resolve,reject)=>{
axios.post(url,data).then((response)=>{
console.log('请求成功',response.data);
if(response.data && isErrorCode(response.data.code)){
let title = errorTitle(response.data.code);
let info = errorInfo(response.data.code);
}
resolve(response)
})
.catch((error)=>{
console.log('请求失败',error)
reject(error)
})
});
console.log('promise.then',promise.then)
console.log('promise.catch',promise.catch)
return promise;
}

config文件中的index.js设置baseUrl
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: './',
proxyTable: {
'/': {
target: 'http://test.wulian.81dd.cn', //测试
changeOrigin: true
}
},
}
posted @ 2019-05-20 17:56  小码哥-倩倩  阅读(454)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3