模拟axios

搭建HTTP 服务

json-server网址:json-server - npm

axios 对象创建模拟实现

axios既可以当做函数直接调用,也可以当做对象调用内部函数 – 先生成函数,再往函数原型上加方法

	// 构造函数
	 function Axios(config){
   
	     // 初始化
	     this.defaults = config, //为了创建defaults的默认属性
	     // 拦截器
	     this.intercepters = {
   
	         request: {
   },
	         response: {
   }
	     }
	 }
	 /**
	  * 原型添加相关的方法
	  * axios 请求最终都是通过调用request方法去请求XMLHttpRequest
	 */
	 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) {
   
	     /**
	      * 实例化一个对象
	      * 可以context.get() context.post(), 但是不能当做函数使用 context()
	     */
	     let context = new Axios(config);
	     /**
	      * 创建请求函数
	      * instance 可以当做一个函数调用 instance(),
	      * 此时instance.get(), instance.post() 不能用
	     */
	     let instance = Axios.prototype.request.bind(context); 
	     // 将 Axios.prototype 对象中的方法添加到 instance 函数对象中
	     Object.keys(Axios.prototype).forEach(key => {
   
	         instance[key] = Axios.prototype[key].bind(context); // 让方法始终指向 context 实例
	     })
	     Object.keys(context).forEach(key => {
   
	         instance[key] = context[key]
	     })
	     return instance
	 }
	
	 let axios = createInstance()
	 axios({
   method: 'get'})
	 axios.get()
	 axios.post()

模拟axios实现发送请求

axios 是基于 promise 的http客户端,可在浏览器与node.js 服务器上发送请求
axios 是对 XMLHttpRequest的封装
axios 请求过程: axios 调用 request ,request 再调用 dispatch(适配器),dispatch 再调用 xhr。再逐步往回返回结果xhr -> dispatch -> request -> axios

	 // axios 发送请求, axios Axios.prototype.request bind
	 //1. 构造函数
	  function Axios(config){
   
	     this.config = config
	  }
	  Axios.prototype.request = function(config) {
   
	     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值