1.为什么 axios 既可以当函数调用,也可以当对象使用,比如axios({}) axios.get
axios() 当函数调用:
- 因为构造函数中,返回的实例就是一个 wrap 函数,在 wrap 函数中返回的是 Axios.prototype.request 函数
- axios() = instance() = wrap() = Axios.prototype.request.call(context)
axios.get 当对象调用:
- 在构造函数中使用 extend 方法,将 Axios.prototype 上的属性方法拷贝 instance
- 在 Axios.prototype[method] 中,返回的是 this.request 这个方法
- 所以 axios.get() = instace.get = Axios.prototype.get() = Axios.prototype.request()
注意:无论哪种方法调用最后都是执行 Axios.prototype.request() 这个方法
2.简述 axios 调用流程
- 实际是调用的 Axios.prototype.request 方法
- 最终返回的是 promise 链式调用,实际请求是在 dispatchRequest 中派发的
3.有用过拦截器吗?原理是怎样的?
- axios.interceptors.request.use 添加请求成功和失败拦截器函数
- axios.interceptors.response.use 添加响应成功和失败拦截器函数
- 在 Axios.prototype.request 维护一个数组
- 然后通过 Interceptors.protype.forEach 将拦截器存入 dispatchRequest 的两端,然后都放入该数组
- 然后通过循环该数组,组成 promise 链
- 从而做到请求前拦截和响应后拦截
注意:dispatchRequest 用于处理适配器adapter发送请求
5.为什么支持浏览器中发送请求也支持 node 发送请求?
- 使用的是适配器的模式
- 在 defaults.js 文件中去判断环境,然后根据环境使用对应的适配器
- 在 axios.defaults.adapter 中可以找到