axios知识点

一、服务端和axios请求之间传参

data—body
  • axios请求使用data携带参数,服务端使用req.body接收
axios({
  //请求类型
  method: 'POST',
  //URL
  url: 'http://127.0.0.1:8001/api/addUser',
  //设置请求体
  data: {
    id: 18,
    username: 'admin18',
    password: '000000',
    nickname: 'admin999',
    email: '333@qq.com',
    user_ic: ''
  }
}).then((response) => {
  console.log(response)
})
  • data的数据格式为一个对象时,在服务端要使用内置中间件将其转化成json格式数据,否则传递过来的数据为空对象
app.use(express.json())
:arg—params
  • axios请求中在url地址中使用:arg形式传递一个参数时,在服务端要使用params接收一个对象

二、axios发起请求

get
axios({
  //请求类型
  method: 'GET',
  //URL
  url: 'http://127.0.0.1:8001/api/user/33'
}).then((response) => {
  console.log(response)
})
post
axios({
  //请求类型
  method: 'POST',
  //URL
  url: 'http://127.0.0.1:8001/api/addUser',
  //设置请求体
  data: {
    id: 33,
    username: 'admin33',
    password: '000000',
    nickname: 'admin999',
    email: '333@qq.com',
    user_ic: ''
  }
}).then((response) => {
  console.log(response)
})
put
axios({
  //请求类型
  method: 'PUT',
  //URL
  url: 'http://127.0.0.1:8001/api/updateUser/33',
  //设置请求体
  data: {
    username: '你好好笑',
    nickname: '我不好笑'
  }
}).then((response) => {
  console.log(response)
})
delete
axios({
  //请求类型
  method: 'delete',
  //URL
  url: 'http://127.0.0.1:8001/api/deleteUser/33'
}).then((response) => {
  console.log(response)
})
axios.request()
axios
  .request({
    method: 'GET',
    url: 'http://127.0.0.1:8001/api/user/34'
  })
  .then((response) => {
    console.log(response)
  })
axios.post()
axios
  .post('http://127.0.0.1:8001/api/addUser', {
    id: 34,
    username: 'admin34',
    password: '000000',
    nickname: 'admin999',
    email: '333@qq.com',
    user_ic: ''
  })
  .then((response) => {
    console.log(response)
  })

三、默认配置

const btns = document.querySelectorAll('button')
//默认配置
axios.defaults.method = 'GET' //设置默认的请求类型为 GET
axios.defaults.baseURL = 'http://127.0.0.1:8001' //设置基础 URL
//   axios.defaults.params = { id: 33 }
axios.defaults.timeout = 10 //限制时间10ms
btns[0].onclick = function () {
  axios({
    url: '/api/user/33'
  }).then((response) => {
    console.log(response)
  })
}

四、创建axios实例发起请求

const duanzi = axios.create({
  baseURL: 'http://127.0.0.1:8001',
  timeout: 2000
})
duanzi.get('/api/user/33').then((response) => {
  console.log(response.data)
})

五、拦截器

  • 本质上就是一个函数
  • 请求拦截器:发送请求之前可以通过回调函数,检测请求的内容和参数,如果请求有问题,就可以通过请求拦截器中止请求
  • 响应拦截器:对请求失败或成功的结果进行处理
请求拦截器
axios.interceptors.request.use(
  function (config) {
    console.log('请求拦截器 成功 - 1号')
    //修改 config 中的参数
    config.params = { a: 100 }
    return config
  },
  function (error) {
    console.log('请求拦截器 失败 - 1号')
    return Promise.reject(error)
  }
)
响应拦截器
axios.interceptors.response.use(
  function (response) {
    console.log('响应拦截器 成功 1号')
    return response.data
    // return response;
  },
  function (error) {
    console.log('响应拦截器 失败 1号')
    return Promise.reject(error)
  }
)

六、取消请求

const btns = document.querySelectorAll('button')
//2.声明全局变量
let cancel = null
//发送请求
btns[0].onclick = function () {
  //检测上一次的请求是否已经完成,避免连续多次发起请求,造成服务器压力过大
  if (cancel !== null) {
    //取消上一次的请求
    cancel()
  }
  axios({
    method: 'GET',
    url: 'http://127.0.0.1:8001/api/user/33',
    //1. 添加配置对象的属性
    cancelToken: new axios.CancelToken(function (c) {
      //3. 将 c 的值赋值给 cancel
      cancel = c
    })
  }).then((response) => {
    console.log(response)
    //将 cancel 的值初始化
    cancel = null
  })
}
//绑定第二个事件取消请求
btns[1].onclick = function () {
  cancel()
}

七、axios对象的简单实现

//构造函数
function Axios(config) {
  //初始化
  this.defaults = config //为了创建 default 默认属性
  this.intercepters = {
    request: {},
    response: {}
  }
}
//原型添加相关的方法
Axios.prototype.request = function (config) {
  console.log('发送 AJAX 请求 请求的类型为 ' + config.method)
}
Axios.prototype.get = function (config) {
  return this.request({ method: 'GET' })
}
Axios.prototype.post = function (config) {
  return this.request({ method: 'POST' })
}
//声明函数
function createInstance(config) {
  //实例化一个对象
  let context = new Axios(config) // context.get()  context.post()  但是不能当做函数使用 context() X
  //创建请求函数
  let instance = Axios.prototype.request.bind(context) // instance 是一个函数 并且可以 instance({})  此时 instance 不能 instance.get X
  //将 Axios.prototype 对象中的方法添加到instance函数对象中
  Object.keys(Axios.prototype).forEach((key) => {
    instance[key] = Axios.prototype[key].bind(context) // this.default  this.interceptors
  })
  //为 instance 函数对象添加属性 default 与 interceptors
  Object.keys(context).forEach((key) => {
    instance[key] = context[key]
  })
  return instance
}
let axios = createInstance()
//发送请求
// axios({method:'POST'});
axios.get({})
axios.post({})

八、axios请求发送简单实现

// axios 发送请求   axios  Axios.prototype.request  bind
//1. 声明构造函数
function Axios(config) {
  this.config = config
}
Axios.prototype.request = function (config) {
  //发送请求
  //创建一个 promise 对象
  let promise = Promise.resolve(config)
  //声明一个数组
  let chains = [dispatchRequest, undefined] // undefined 占位
  //调用 then 方法指定回调
  let result = promise.then(chains[0], chains[1])
  //返回 promise 的结果
  return result
}
//2. dispatchRequest 函数
function dispatchRequest(config) {
  //调用适配器发送请求
  return xhrAdapter(config).then(
    (response) => {
      //响应的结果进行转换处理
      //....
      return response
    },
    (error) => {
      throw error
    }
  )
}
//3. adapter 适配器
function xhrAdapter(config) {
  console.log('xhrAdapter 函数执行')
  return new Promise((resolve, reject) => {
    //发送 AJAX 请求
    let xhr = new XMLHttpRequest()
    //初始化
    xhr.open(config.method, config.url)
    //发送
    xhr.send()
    //绑定事件
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        //判断成功的条件
        if (xhr.status >= 200 && xhr.status < 300) {
          //成功的状态
          resolve({
            //配置对象
            config: config,
            //响应体
            data: xhr.response,
            //响应头
            headers: xhr.getAllResponseHeaders(), //字符串  parseHeaders
            // xhr 请求对象
            request: xhr,
            //响应状态码
            status: xhr.status,
            //响应状态字符串
            statusText: xhr.statusText
          })
        } else {
          //失败的状态
          reject(new Error('请求失败 失败的状态码为' + xhr.status))
        }
      }
    }
  })
}
//4. 创建 axios 函数
let axios = Axios.prototype.request.bind(null)
axios({
  method: 'GET',
  url: 'http://127.0.0.1:8001/api/user/33'
}).then((response) => {
  console.log(response)
})

九、拦截器简单实现和使用

//构造函数
function Axios(config) {
  this.config = config
  this.interceptors = {
    request: new InterceptorManager(),
    response: new InterceptorManager()
  }
}
//发送请求  难点与重点
Axios.prototype.request = function (config) {
  //创建一个 promise 对象
  let promise = Promise.resolve(config)
  //创建一个数组
  const chains = [dispatchRequest, undefined]
  //处理拦截器
  //请求拦截器 将请求拦截器的回调 压入到 chains 的前面  request.handles = []
  this.interceptors.request.handlers.forEach((item) => {
    chains.unshift(item.fulfilled, item.rejected)
  })
  //响应拦截器
  this.interceptors.response.handlers.forEach((item) => {
    chains.push(item.fulfilled, item.rejected)
  })
  // console.log(chains);
  //遍历
  while (chains.length > 0) {
    // shift用于删除数组第一个元素,并返回该元素的值
    promise = promise.then(chains.shift(), chains.shift())
  }
  return promise
}
//发送请求
function dispatchRequest(config) {
  //返回一个promise 队形
  return new Promise((resolve, reject) => {
    resolve({
      status: 200,
      statusText: 'OK'
    })
  })
}
//创建实例
let context = new Axios({})
//创建axios函数
let axios = Axios.prototype.request.bind(context)
//将 context 属性 config interceptors 添加至 axios 函数对象身上
Object.keys(context).forEach((key) => {
  axios[key] = context[key]
})
//拦截器管理器构造函数
function InterceptorManager() {
  this.handlers = []
}
InterceptorManager.prototype.use = function (fulfilled, rejected) {
  this.handlers.push({
    fulfilled,
    rejected
  })
}
//以下为功能测试代码
// 设置请求拦截器  config 配置对象
axios.interceptors.request.use(
  function one(config) {
    console.log('请求拦截器 成功 - 1号')
    return config
  },
  function one(error) {
    console.log('请求拦截器 失败 - 1号')
    return Promise.reject(error)
  }
)
axios.interceptors.request.use(
  function two(config) {
    console.log('请求拦截器 成功 - 2号')
    return config
  },
  function two(error) {
    console.log('请求拦截器 失败 - 2号')
    return Promise.reject(error)
  }
)
// 设置响应拦截器
axios.interceptors.response.use(
  function (response) {
    console.log('响应拦截器 成功 1号')
    return response
  },
  function (error) {
    console.log('响应拦截器 失败 1号')
    return Promise.reject(error)
  }
)
axios.interceptors.response.use(
  function (response) {
    console.log('响应拦截器 成功 2号')
    return response
  },
  function (error) {
    console.log('响应拦截器 失败 2号')
    return Promise.reject(error)
  }
)
//发送请求
axios({
  method: 'GET',
  url: 'http://127.0.0.1:8001/api/user/33'
}).then((response) => {
  console.log(response)
})

十、取消请求的简单实现

//构造函数
function Axios(config) {
  this.config = config
}
//原型 request 方法
Axios.prototype.request = function (config) {
  return dispatchRequest(config)
}
//dispatchRequest 函数
function dispatchRequest(config) {
  return xhrAdapter(config)
}
//xhrAdapter
function xhrAdapter(config) {
  //发送 AJAX 请求
  return new Promise((resolve, reject) => {
    //实例化对象
    const xhr = new XMLHttpRequest()
    //初始化
    xhr.open(config.method, config.url)
    //发送
    xhr.send()
    //处理结果
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        //判断结果
        if (xhr.status >= 200 && xhr.status < 300
          //设置为成功的状态
          resolve({
            status: xhr.status,
            statusText: xhr.statusText
          })
        } else {
          reject(new Error('请求失败'))
        }
      }
    }
    //关于取消请求的处理
    if (config.cancelToken) {
      //对 cancelToken 对象身上的 promise 对象指
      config.cancelToken.promise.then((value) => 
        xhr.abort()
        //将整体结果设置为失败
        reject(new Error('请求已经被取消'))
      })
    }
  })
}
//创建 axios 函数
const context = new Axios({})
const axios = Axios.prototype.request.bind(contex
//CancelToken 构造函数
function CancelToken(executor) {
  //声明一个变量
  var resolvePromise
  //为实例对象添加属性
  this.promise = new Promise((resolve) => {
    //将 resolve 赋值给 resolvePromise
    resolvePromise = resolve
  })
  //调用 executor 函数
  executor(function () {
    //执行 resolvePromise 函数
    resolvePromise()
  })
}
//获取按钮 以上为模拟实现的代码
const btns = document.querySelectorAll('button')
//2.声明全局变量
let cancel = null
//发送请求
btns[0].onclick = function () {
  //检测上一次的请求是否已经完成
  if (cancel !== null) {
    //取消上一次的请求
    cancel()
  }
  //创建 cancelToken 的值
  let cancelToken = new CancelToken(function (c) 
    cancel = c
  })
  axios({
    method: 'GET',
    url: 'http://127.0.0.1:8001/api/user/33',
    //1. 添加配置对象的属性
    cancelToken: cancelToken
  }).then((response) => {
    console.log(response)
    //将 cancel 的值初始化
    cancel = null
  })
}
//绑定第二个事件取消请求
btns[1].onclick = function () {
  cancel()
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值