vue 项目axios全局配置与路由模式配置

axios全局配置

vue项目的一般都会用axios作为http请求,如果是后台管理之类的项目往往会涉及权限或者全局异常处理配置,下面是配置axios全局拦截器的示例代码(main.js文件)

javascript 复制代码
//main.js
import Vue from 'vue';
import iView from 'iview';
import 'iview/dist/styles/iview.css';
import Util from './libs/util';
import axios from 'axios';
import cacheUtil from './libs/cache_util';
import cfg from './libs/server_config.js';

axios.defaults.baseURL = cfg.baseUrl;
axios.defaults.method = 'post';

axios.interceptors.request.use(
  config => {
    let u_token = cacheUtil.getCache('u_token');
    if (u_token != null) {
      config.headers['Authorization'] = u_token;
    }
    return config;
  }, function (error) {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(function (response) {
  // 请求未授权
  if (response.data.ret_code === 401) {
    return Promise.reject(response);
  } else if (response.data.ret_code !== 200) {
    iView.Notice.error({title: '请求出错! 错误码: ' + response.data.ret_code, desc: response.data.ret_msg});
    if (response.data.ret_msg === "session 失效,请重新登陆!") {
      // 退出登录
      router.push({
        name: 'login'
      });
    }
    return Promise.reject(response);
  }
  return response.data.data;
}, function (error) {
  console.log(error);
  iView.Notice.error({title: '请求出错! ', desc: '网络连接失败!'});
  return Promise.reject(error);
});

Vue.prototype.$axios = axios;

//配置路由
export default new Router({
  base: 'page',
  mode: 'history', //这里配置路由的模式
  routes: [
    {
      path: '/login',
      name: 'login',
      component: login
    },
]
});

vue路由配置

1 hash模式

路由默认模式是hash模式,hash模式的关键原理是onhashchange事件,无需向后端发起请求,浏览器可以监听Hash值的变化,并按规则加载相应的代码。Hash值的变化会被浏览器记录,实现页面的前进和后退功能,但url地址会有#号符,可能能些人会感觉不美观。

2 history模式

history模式的URL中没有#符号,采用传统的路由分发模式,即用户输入URL时,服务器接收请求并解析URL,然后进行相应的逻辑处理,也就说所有的页面切换都经过了后台,后台服务器资源相对比hash相对消耗,不过没有太大的访问量也体现不出那点差距。

相关推荐
程序员Sunday3 小时前
JavaScript 事件循环面试题,宏任务与微任务怎么执行|Sunday面试指南
开发语言·javascript·面试·校招·事件循环·程序员sunday
Setsuna_F_Seiei3 小时前
前端转型 Agent 开发 06 之 Agent Memory 记忆系统(让 Agent 更智能,更懂你)
前端·agent·ai编程
志尊宝4 小时前
Vue3 零基础每日笔记(073):keep-alive 页面缓存实战——列表页返回不丢状态
vue.js·笔记·缓存·#vue #前端 #前端开发·#javascript·#vue.js
zhangzeyuaaa4 小时前
Ruby 多线程、GVL(GIL)与 Mutex 完全指南
开发语言·前端·ruby
默_笙4 小时前
🌊 向量库和 ES 都查不出"关系",我只好给奶茶建了一张人脉网
前端·javascript
优选资讯5 小时前
标签打印软件怎么对接 Excel 数据
前端·excel
思无邪665 小时前
用 AI 做 JS 逆向:从抓包到复现的完整方法论
开发语言·javascript·人工智能
一个风轻云淡6 小时前
GCC 和 GDB命令简单解读
java·linux·前端
u0111026756 小时前
图片处理接口如何统一错误信息 前端提示与后端错误码设计
前端·状态模式
福兮说7 小时前
浏览器里把 iPhone 的 HEIC 转成 JPG:Chrome 解不开、转完大了七成、拍摄时间全丢,六个坑实测
前端·javascript·图像处理·chrome·ios·iphone·heic