All Projects → superman66 → Vue Axios Github

superman66 / Vue Axios Github

Licence: mit
Vue 全家桶 + axios 前端实现登录拦截、登出、拦截器等功能

Programming Languages

javascript
184084 projects - #8 most used programming language
Vue
7211 projects
HTML
75241 projects

Projects that are alternatives of or similar to Vue Axios Github

Vue Project
基于vue-cli构建的财务后台管理系统(vue2+vuex+axios+vue-router+element-ui+echarts+websocket+vue-i18n)
Stars: ✭ 301 (-88.52%)
Mutual labels:  axios, vuex, vuejs2, vue-router
Vue Cnode
🔥Vue.js打造一个开源的CNode社区。CNode by Vue.js
Stars: ✭ 249 (-90.5%)
Mutual labels:  axios, vuex, vuejs2, vue-router
Vue Music
cloud-music(网易云音乐)
Stars: ✭ 500 (-80.93%)
Mutual labels:  axios, vuex, vuejs2, vue-router
Vue Home
🏠 A simple project(Vue Community SPA) which bases on vue+vue-cli+vue-router+axios+ scss.
Stars: ✭ 256 (-90.24%)
Mutual labels:  axios, vuex, vuejs2, vue-router
Vue Music Player
🎵Vue.js写一个音乐播放器+📖One(一个).A music player + One by Vue.js
Stars: ✭ 729 (-72.2%)
Mutual labels:  axios, vuex, vuejs2, vue-router
Vue Fallowfish
🐠vue全家桶仿闲鱼部分布局以及功能实现
Stars: ✭ 211 (-91.95%)
Mutual labels:  axios, vuex, vue-router
Vuetify Todo Pwa
✔️ A simple Todo PWA built with Vue CLI 3 + Vuex + Vuetify.
Stars: ✭ 160 (-93.9%)
Mutual labels:  vuex, vuejs2, vue-router
Vue Blog
🎉 基于vue全家桶 + element-ui 构建的一个后台管理集成解决方案
Stars: ✭ 208 (-92.07%)
Mutual labels:  axios, vuex, vue-router
Nx Admin
👍 A magical 🐮 ⚔ vue admin,记得star
Stars: ✭ 2,497 (-4.77%)
Mutual labels:  axios, vuex, vuejs2
Laravue
Admin dashboard for enterprise Laravel applications built by VueJS and Element UI https://laravue.dev
Stars: ✭ 1,964 (-25.1%)
Mutual labels:  axios, vuex, vue-router
Symfony Vuejs
Source code of the tutorial "Building a single-page application with Symfony 4 and Vue.js"
Stars: ✭ 170 (-93.52%)
Mutual labels:  axios, vuex, vue-router
Copilot
Responsive Bootstrap 3 Admin Template based on AdminLTE with vue.js
Stars: ✭ 2,698 (+2.9%)
Mutual labels:  vuex, vuejs2, vue-router
Venture Management
一个包含vuejs和nodejs技术的全栈项目
Stars: ✭ 208 (-92.07%)
Mutual labels:  axios, vuex, vue-router
Gpk admin
✨ GeekPark Content Management System
Stars: ✭ 150 (-94.28%)
Mutual labels:  vuex, vuejs2, vue-router
Vue Objccn
🔥 Use Vue.js to develop a cross-platform full stack application / 用 Vue.js 开发的跨三端应用
Stars: ✭ 1,993 (-23.99%)
Mutual labels:  vuex, vuejs2, vue-router
Vue Shop
VUE移动小商城
Stars: ✭ 148 (-94.36%)
Mutual labels:  axios, vuex, vue-router
Vue2 Demo
Vue 基于 Genesis + TS + Vuex 实现的 SSR demo
Stars: ✭ 2,072 (-20.98%)
Mutual labels:  vuex, vuejs2, vue-router
Vue Electron
vue-blog client,base on vue-electron,axios, vuex, vue-router.
Stars: ✭ 193 (-92.64%)
Mutual labels:  axios, vuex, vue-router
Vue Cnode
🚀 基于vue3 function-based 构建cnode社区
Stars: ✭ 192 (-92.68%)
Mutual labels:  axios, vuex, vue-router
Lvyou
🎒Vue.js 初步进阶案例,路由懒加载,进入页面前登录判断,返回导航判断,RestAPI接口使用,组件封装,Vuex状态封装,keep-alive页面缓存等功能
Stars: ✭ 195 (-92.56%)
Mutual labels:  vuex, vuejs2, vue-router

Travis

一个项目学会前端实现登录拦截

一个项目学会vue全家桶+axios实现登录、拦截、登出功能,以及利用axios的http拦截器拦截请求和响应。

点击这里查看👉 Demo

页面打不开?可能你需要翻墙。点击查看翻墙推荐

前言

该项目是利用了Github 提供的personal token作为登录token,通过token访问你的Repository List。通过这个项目学习如何实现一个前端项目中所需要的 登录及拦截、登出、token失效的拦截及对应 axios 拦截器的使用。

准备

你需要先生成自己的 Github Personal Token(生成Token)。 Token 生成后 访问 Demo,即可查看你的Repository List。

项目结构

.
├── README.md
├── dist  // 打包构建后的文件夹
│   ├── build.js
│   └── build.js.map
├── index.html
├── package.json
├── src
│   ├── App.vue
│   ├── assets
│   │   ├── css.css
│   │   ├── icon.css
│   │   └── logo.png
│   ├── constant
│   │   └── api.js  // 配置api接口文件
│   ├── http.js // 封装fetch、post请求及http 拦截器配置文件
│   ├── index.vue
│   ├── login.vue
│   ├── main.js
│   ├── repository.vue
│   ├── router.js // 路由配置文件
│   └── store
│       ├── store.js  
│       └── types.js  // vuex types
└── webpack.config.js

技术栈

  • Vue 2.0
  • vue-router
  • vuex
  • axios
  • vue-material

登录拦截逻辑

第一步:路由拦截

首先在定义路由的时候就需要多添加一个自定义字段requireAuth,用于判断该路由的访问是否需要登录。如果用户已经登录,则顺利进入路由, 否则就进入登录页面。

const routes = [
    {
        path: '/',
        name: '/',
        component: Index
    },
    {
        path: '/repository',
        name: 'repository',
        meta: {
            requireAuth: true,  // 添加该字段,表示进入这个路由是需要登录的
        },
        component: Repository
    },
    {
        path: '/login',
        name: 'login',
        component: Login
    }
];

定义完路由后,我们主要是利用vue-router提供的钩子函数beforeEach()对路由进行判断。

router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
        if (store.state.token) {  // 通过vuex state获取当前的token是否存在
            next();
        }
        else {
            next({
                path: '/login',
                query: {redirect: to.fullPath}  // 将跳转的路由path作为参数,登录成功后跳转到该路由
            })
        }
    }
    else {
        next();
    }
})

每个钩子方法接收三个参数:

  • to: Route: 即将要进入的目标 路由对象
  • from: Route: 当前导航正要离开的路由
  • next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
    • next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
    • next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
    • next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。

确保要调用 next 方法,否则钩子就不会被 resolved。

完整的方法见/src/router.js

其中,to.meta中是我们自定义的数据,其中就包括我们刚刚定义的requireAuth字段。通过这个字段来判断该路由是否需要登录权限。需要的话,同时当前应用不存在token,则跳转到登录页面,进行登录。登录成功后跳转到目标路由。

登录拦截到这里就结束了吗?并没有。这种方式只是简单的前端路由控制,并不能真正阻止用户访问需要登录权限的路由。还有一种情况便是:当前token失效了,但是token依然保存在本地。这时候你去访问需要登录权限的路由时,实际上应该让用户重新登录。 这时候就需要结合 http 拦截器 + 后端接口返回的http 状态码来判断。

第二步:拦截器

要想统一处理所有http请求和响应,就得用上 axios 的拦截器。通过配置http response inteceptor,当后端接口返回401 Unauthorized(未授权),让用户重新登录。

// http request 拦截器
axios.interceptors.request.use(
    config => {
        if (store.state.token) {  // 判断是否存在token,如果存在的话,则每个http header都加上token
            config.headers.Authorization = `token ${store.state.token}`;
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    });

// http response 拦截器
axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 返回 401 清除token信息并跳转到登录页面
                    store.commit(types.LOGOUT);
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}
                    })
            }
        }
        return Promise.reject(error.response.data)   // 返回接口返回的错误信息
    });

完整的方法见/src/http.js.

通过上面这两步,就可以在前端实现登录拦截了。登出功能也就很简单,只需要把当前token清除,再跳转到首页即可。

运行及构建

# install dependencies
npm install

# serve with hot reload at localhost:8080
npm run dev

# build for production with minification
npm run build
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].