Vue2 Learning-Give Vue2 routing navigation hooks and Axios interceptors a package

Source: Internet
Author: User

1. Write in front

Recently in learning Vue2, encountered some page request data need user login permission, the server response does not meet the expected problem, but always can not each page do alone, so think of Axios provide interceptor this good thing, then appeared this article.

2. Specific requirements
    • User authentication and redirection: Using the routing navigation hooks provided by Vue
    • Request data serialization: Using the request interceptor provided by Axios
    • Interface error Information processing: Using the response interceptor provided by Axios
3. Simple implementation of 3.1 routing navigation hook level authentication and redirection package

Routing navigation hooks All configurations are in Router/index.js, this is part of the code

import Vue from ‘vue‘import Router from ‘vue-router‘import { getUserData } from ‘@/script/localUserData‘const MyAddress = r => require.ensure([], () => r(require(‘@/views/MyAddress/MyAddress‘)), ‘MyAddress‘)Vue.use(Router)const routes = [  {    path: ‘/profile/address‘,    name: ‘MyAddress‘,    component: MyAddress,    meta: {      title: ‘我的地址‘,      requireAuth: true    }  },  // 更多...]const router = new Router({  mode: ‘history‘,  routes})

Let's take a look at the code for the logical processing section below

Let Indexscrolltop = 0router.beforeeach (to, from, next) = {//route before entering the next routed object, determine if a login///In the Routing meta object is required by a requireauth field, only To have this field true, you must do the authentication if (to.matched.some (res = = Res.meta.requireAuth)) {//UserData for some user information stored locally let UserData = ge Tuserdata ()//not logged in and already logged in processing//Getuserdata method after processing if Userdata.token no value is undefined, the following directly determine if (Userdata.token = = = Undefi Ned) {//execute to here the instructions are not logged in, you can do the following on-demand to go to the login page//I have no other processing here, go directly to the login page next ({path: '/login ', query : {Redirect:to.path}})} else {//execute to Description local store has user information//But user information is expired or need to be verified. Drop ov        Erduetime = userdata.overduetime Let Nowtime = +new Date//login expired and not expired if (Nowtime > Overduetime) {            Login expired processing, June can be processed on demand and then perform the following methods to login page//I have no other processing here, go directly to the login page next ({path: '/login ', query: {  Redirect:to.path}})} else {next ()}}} else {next ()} if (To.path !== '/') {IndexscroLltop = document.body.scrollTop} document.title = To.meta.title | | Document.title}) Router.aftereach (route = {if (Route.path!== '/') {document.body.scrollTop = 0} else {Vue. Nexttick (() = {Document.body.scrollTop = indexscrolltop})}) export Default router

At this point, the routing hook level of the authentication process is complete, but careful you may notice: the navigation to the login page to invoke the next method has a query object, carrying the destination route address, because after the successful login we need to redirect to the target page.

3.2 To Axios Interceptor encapsulation

Axios all configurations are in the pieces script/getdata.js file, here is the common Code section of this file

```
Import qs from ' QS '
Import {Getuserdata} from ' @/script/localuserdata '
Import router from ' @/router '
Import Axios from ' Axios '
Import {Ajax_url} from ' @/config/index '
Axios.defaults.baseURL = Ajax_url

> axios请求拦截器代码 ```/** * 请求拦截器,请求发送之前做些事情 */axios.interceptors.request.use(  config => {    // POST || PUT || DELETE请求时先格式化data数据    // 这里需要引入第三方模块qs    if (      config.method.toLocaleUpperCase() === ‘POST‘ ||      config.method.toLocaleUpperCase() === ‘PUT‘ ||      config.method.toLocaleUpperCase() === ‘DELETE‘    ) {      config.data = qs.stringify(config.data)    }    // 配置Authorization参数携带用户token    let userData = getUserData()    if (userData.token) {      config.headers.Authorization = userData.token    }    return config  },  error => {    // 此处应为弹窗显示具体错误信息,因为是练手项目,劣者省略此处    // 君可自行写 || 引入第三方UI框架    console.error(error)    return Promise.reject(error)  })

Axios Response Interceptor Code

/** * response blocker, request return exception Unified processing */axios.interceptors.response.use (response = {//This code is useless in many scenarios if (Response.data &&A mp  Response.data.success = = = False) {//According to the actual situation some processing logic ... return Promise.reject (response)} return response  }, Error = {//error here may be more than//1. Requires that the authority user is not logged in, because the route have authentication is logged in, and here theoretically does not appear//2. Requires a user login to expire//3. Request Error 4xx//      5. Server error 5xx//About authentication failure, with backend Convention status code of "Error.response.status" {Case 403://some processing ... break Case 404://Some processing ... break case 500:let userData = Getuserdata () if (Userdata.token = = = undefined) {//Here is not logged in processing//after some processing ...  Go to login Page ...//Router.push ({//path: '/login '//})} else {Let Overduetime =            Userdata.overduetime Let Nowtime = +new Date if (overduetime && nowtime > Overduetime) { Here login expired processing//after some processing ...  Go to the login page ...//Router.push ({          Path: '/login '//}} else {///extreme case, login not expired, but do not know where the wrong//on-demand processing it.        . I'm violent back home Router.push ({path: '/'}}} break case 501: Some processing ... break default://Status code spicy, on-demand configuration ... break} return Promise.reject (Error)})

Want to learn more about Axios? Please come here.

This package is simple, and certainly requires more consideration in the face of complex business, but almost enough for a small project or edge business. Finally, I hope this article can provide some help to the needy students.

Vue2 Learning-Give Vue2 routing navigation hooks and Axios interceptors a package

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.