axios用法

本文介绍了如何在Vue应用中利用axios库设置请求拦截器和响应拦截器,实现请求前验证token以及处理响应。同时,通过示例展示了如何在Vue中取消一个正在进行的请求,以避免不必要的数据获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.请求拦截器 

这个拦截器会在你发送请求之前运行
应用场景(验证token过期):每一次请求去判断是否有token,如果token存在则在请求头加上这个token。后台会判断这个token是否过期。

import axios from 'axios'

var newAxios =  axios.create({
	baseURL: '/api', // 代理名
	timeout: 10000, // 请求超时事件
	crossDomain: true
})


// 请求拦截器
newAxios.interceptors.request.use(
  (config)=>{
    console.log('请求拦截器1 成功')
    return config
  },
  (error)=>{
    console.log('请求拦截器1 失败')
    return Promise.reject(error)
  }
)

export default newAxios

2.响应拦截器

import axios from 'axios'

var newAxios =  axios.create({
	baseURL: '/api', // 代理名
	timeout: 10000, // 请求超时事件
	crossDomain: true
})


newAxios.interceptors.response.use(
  (response) => {
    console.log('响应拦截器 成功')
    return response
  },
  (error)=>{
    console.log('响应拦截器 失败')
    return Promise.reject(error)
  }
)

export default newAxios

3.取消请求(有坑)

(1).引入axios —— 不要 create axios实例

import Vue from 'vue'
import App from './App.vue'

// 千万不要用 axios.create 出来的实例,因为他没有 axios.CancelToken 构造函数
import axios from 'axios'

// 配置默认路径
axios.defaults.baseURL = '/api'

// 将axios挂载到Vue上
Vue.prototype.axios = axios

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

(2).发送/取消请求

<template>
  <div id="app">
    <button @click="sendAjax">发送请求</button>
    <br>
    <br>
    <button @click="cancelAjax">取消请求</button>
  </div>
</template>

<script>


export default {
  name: 'App',
  data(){
    return {
      cancel:''
    }
  },
  methods:{
    sendAjax(){
      this.axios({
        url:'/hello',
        // 添加一个配置项,接收取消请求的函数
        cancelToken:new this.axios.CancelToken((c)=>{
          this.cancel = c
        })
      }).then(res=>{
        console.log('请求成功',res)
      }).catch((err)=>{  // 这里一定要接 .catch 不然会报错
        console.log(err)
      })
    },
    cancelAjax(){
      // 判断 当前是不是有请求正在发送
      if(typeof this.cancel === 'function'){
        this.cancel('请求被强制取消了')
      }
    }
  }
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值