How to use Axios in Vue

First introduce what is Axios:

        Axios is a promise-based HTTP library that can be used in browsers and node.js

        The main function is to initiate a request to the background

Let's first understand what a promise is?

       1. Mainly used for asynchronous computing

       2. Asynchronous operations can be queued, executed in the desired order, and return results that meet the expectations

So how to use axios in Vue?

The first step: Install axios:

npm install --save axios

Step 2: Import axios in main.js of vue 

How to request a lot of paths, and their prefixes are all the same, we can set a unified prefix, it will be very convenient for later use (also in the main.js file).

Step 3: Design the default routing prefix

axios.defaults.baseURL='/test'

Below we can use it in the page

<template>
  <div class="login">
    <div>赫于富你好,欢迎登录</div>
  </div>
</template>
<script>
export default {
  methods: {
    test () {
       this.$axios.get("/hahceshi")
    }
  },
  created () {
    this.test();
  },
}
</script>

You can see that we only wrote when requesting

But the real request is with the default prefix. This greatly improves the availability of the system.

If you have understood the usage above, then we will make further improvements below

Encapsulate an axios with interceptor based on the official axios

The first step: clear the configuration of axios we just made in main.js

Add a utils folder-->interceptor.js file

Import axios in this file

//在官方的axios的基础上封装一个添加拦截器的axios
import axios from 'axios'
//配置默认的路由地址头
axios.defaults.baseURL = '/test'
//全局添加拦截器的作用是可以在每个api前面加上headers的token验证
axios.interceptors.request.use(config => {
  // 判断token是否存在和是否需要token验证的路由
  if (sessionStorage.getItem('token')) {
    config.headers.Authorization = sessionStorage.getItem('token');
  }
  return config;
})
export default axios

So where do you get the token data? 

       When you log in for the first time, if you log in successfully for the first time, you can get the token value. Requests after entering the system will carry the token value. The current system we do is that if the token value expires or is lost, it will return To the login interface

Step 2: Set the token value in login.vue

<script>
export default {
  name: 'Login',
  methods: {
    test () {
       this.$axios.get("/hahceshi")
       //因为是测试,所以默认是登录成功的,这里省略了登录成功的判断
        //登录成功之后把token信息保存到sessionStorage中
        sessionStorage.setItem("token", 'heyufuToken');
    }
  },
  created () {
    this.test();
  },
}
</script>

After the login is successful, we can check SessionStorage and find that the value is already there:

Then you can carry this token value in future pages unless the token expires

have a test:

interface:

Code:

operation result: 

Jump result The token value will always exist after successful jump:

So how to detect that the token value is lost and our route will automatically jump to the login page?

Add to the routing file Mount the routing navigation guard:

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径  from 从哪个路径跳转过来  next 一个函数,表示放行
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

 

Guess you like

Origin blog.csdn.net/qq_30631063/article/details/107099336