axios 原理

安装:npm install axios

基础使用:

axios发送请求:

//发送AJAX请求
axios({
  //请求类型
  method:'GET',
  //URL
  url:'',
  //axios返回一个promise对象,成功用.then接受返回结果
}).then(response=>{
  console.log(response)
})

//发送AJAX请求
axios({
  //请求类型
  method:'POST',
  //URL
  url:'',
  //设置请求体
  data:{
    title:'',
    author:''
  }
  //axios返回一个promise对象,成功用.then接受返回结果
}).then(response=>{
  console.log(response)
})

//发送AJAX请求
axios({
  //请求类型
  method:'PUT',
  //URL
  url:'',
  //设置请求体
  data:{
    title:'',
    author:''
  }
  //axios返回一个promise对象,成功用.then接受返回结果
}).then(response=>{
  console.log(response)
})

//发送AJAX请求
axios({
  //请求类型  删除请求大小写都行
  method:'delete',
  //URL
  url:'',
  //axios返回一个promise对象,成功用.then接受返回结果
}).then(response=>{
  console.log(response)
})

axios方法发送请求(很多方法)

//发送GET请求
//axios()
axios.request({
  //请求类型
  method:'GET',
  //URL
  url:'',
  //request请求返回一个promise对象,成功用.then接受返回结果
}).then(response=>{
  console.log(response)
})

//发送POST请求
//post请求接受到三个参数
//第一个参数要请求的接口
//第二个参数要发送的参数数据(可选)
//第三个参数配置对象(可选)
//axios()
axios.post(
  	'接口',
  {
    'body':'',
    'postId':''
  }).then(response=>{
  //post请求返回一个promise对象,成功用.then接受返回结果
    console.log(response)
  })

axios的设置默认配置

axios创建实例对象

备注:如果有多个服务器可以创建多个实例对象

拦截器

//内部原理Promise
    //设置请求拦截器
    axios.interceptors.request.use(function(config){
      console.log('请求拦截器 成功');
      //设置请求时间
      config.timeout = 2000
      return config
    },function(error){
      console.log('请求拦截器失败');
      return Promise.reject(error)
    })
    //设置响应拦截器
    axios.interceptors.response.use(function(response){
      console.log('响应拦截器 成功');
      return response
    },function(error){
      console.log('响应拦截器 失败');
      return Promise.reject(error)
    })
    axios({
      method:'GET',
      url:'http://localhost:3000/posts'
    }).then(response=>{
      console.log('成功的回调',response);
    }).catch(reject=>{
      console.log('失败的回调',reject);
    })

取消请求

//2.声明全局变量
    let cancel = null 
    //检测上一次的请求是否完成
    if(cancel != null){
      // 取消上一次的请求
      cancel()
    }
    axios({
      method:"GET",
      url:'http://localhost:3000/posts',
      //1.添加配置对象属性
      cancelToken:new axios.CancelToken(function(c){
        //将c赋值给cancel
        cancel = c
      })
    }).then(response=>{
      console.log(response);
      //成功后将cancel的值初始化
    })
    //取消请求
    cancel()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值