记录封装好的axios

拦截封装

import axios from "axios";
import {Notify, Toast} from 'vant';
import router from "../router";
export function request(config) {
    const instance = axios.create({
        // 设置请求头
        baseURL: 'https://api.shop.eduwork.cn',
        // 设置请求时间
        // timeout: 1000
    })

    // 请求拦截
    instance.interceptors.request.use(config => {
        // 如果有一些接口需要认证才可以访问,就在这统一设置
        const token = window.localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = 'Bearer' + token;
        }
        // 直接放行
        return config;
    },error => {

    })

    // 相应拦截
    instance.interceptors.response.use(res => {
        return res.data ? res.data : res;
    },error => {
        // 如果有需要授权才可以访问的接口,统一去login授权
        if (error.response.status == '401'){
            Toast.fail('请先登录');
            router.push({path:'/login'});
        }
        // 如果有错误,这里面去设置处理,显示错误信息
        Notify(error.response.data.errors[Object.keys(error.response.data.errors)[0]][0])
    })
    return instance(config);
}

路由封装

import { createRouter, createWebHistory } from 'vue-router'
import store from '../store';
import {Notify} from "vant";
const Home = () => import('views/home/Home');
const Category = () => import('views/category/Category');
const Detail = () => import('views/detail/Detail');
const Profile = () => import('views/profile/Profile');
const Shopcart = () => import('views/shopcart/Shopcart');
const Register = () => import('views/profile/Register');
const Login = () => import('views/profile/Login');
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: '图书兄弟-首页'
    }
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      title: '图书兄弟-首页'
    }
  },
  
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
router.beforeEach((to,from,next) => {
  // 如果没有登陆,在这里到login
  if (to.meta.isAuthRequired && store.state.user.isLogin === false){
    Notify('您还没有登录,请登录先');
    return next('/login');
  }else {
    next();
  }
  document.title = to.meta.title;
})

export default router

你可能感兴趣的:(记录封装好的axios)