zoukankan      html  css  js  c++  java
  • axios学习笔记

    1.将axios挂载到Vue原型上,实现组件的直接使用

    背景:Vue中多组件每次都需要

    import axios from 'axios'

    后才能使用axios发送请求,在项目入口main.js中可以采用将axios挂载到Vue原型上,这样组件(Vue的实例)就可以直接访问了

    //main.js中引入一次,并挂载
    import axios from 'axios'
    Vue.prototype.$http = axios
    
    //在其他组件中可以直接使用
    this.$http(url地址,参数).then()....

    2.配置axios请求地址的公共路径以简化代码

    //在入口文件main.js中配置
    axios.defaults.baseURL = '公共路径'
    
    //在组件中使用时
    axiso.('/后缀路径',参数).then()...

    3.axios的请求拦截器与响应拦截器

    背景:当每次请求数据都要设置请求头信息时,采用请求拦截器实现请求头设置以简化代码

    axios.interceptors.request.use(function (config) {
      //    console.log('请求已经被拦截')
      console.log(config)
      if (!config.url.endsWith('/login')) {
        config.headers.Authorization = localStorage.getItem('token')
      }
      return config
    })

    响应拦截器(暂时还不太理解这个的用法)(当token信息验证失败,直接跳转到登录页)

    axios.interceptors.response.use(function (response) {
      //    console.log('响应已经被拦截')
      console.log(response)
      if (response.data.meta.status === 401) {
        router.push('/login')
        localStorage.removeItem('token')
      }
      return response
    })
  • 相关阅读:
    php 验证码
    扫描登录
    正则表达式
    liunx 搭建svn
    jq
    spl_autoload_register()函数
    php函数操作文件
    配置nginx支持TP框架
    Object-c 访问控制
    Obiective
  • 原文地址:https://www.cnblogs.com/zhou-135/p/11664163.html
Copyright © 2011-2022 走看看