拿起Typescript做一个轮子(三)
Url处理
需求分析
- 把params参数拼接到url上,参数值支持对对象、数组、Date、特殊字符串的处理,丢弃url中的哈希标记,保留url中已存在的参数
因为在处理url时需要对日期和对象类型进行特殊的处理,所以我们在util.ts里编写两个判断日期和对象的方法
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/b167617ba58a49f8a3fe9e0cf6b22590.jpg)
文章图片
然后在encodeurl时需要对特殊字符再转义回来
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/2ccb8ea86f4b4298bf7f6e5a7fb5d7f7.jpg)
文章图片
【拿起Typescript做一个轮子(三)】处理url的逻辑
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/f11454033a9e4bfbb603b39da7c5bbfe.jpg)
文章图片
然后我们把url处理的逻辑应用到请求当中
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/44870e3bf8234ec0aaec109e024917f8.jpg)
文章图片
Data处理 在helpers下新建个data.ts文件,存放我们处理data的逻辑
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/cd3e88bddac741578e984ac0e0e47be5.jpg)
文章图片
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/37c407e2265c4005ae8be9a53b69bf77.jpg)
文章图片
Header处理 需求分析
- 支持在发送请求时可以设置headers属性
- 并且当传入data为普通对象时,headers如果没有配置Content-Type属性,需要自动设置请求header的Content-Type字段为:application/json; charset=utf-8
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/835f122d55704110bf5c7e1bf422b175.jpg)
文章图片
然后在processConfig方面里使用,注意这里对headers的处理要在data之前,因为transformRequestData方法会把data转成JSON字符串,那么我们的processHeaders方法就不能判断data为对象了
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/fa05a5d8c15640988c5bdb86653de1c7.jpg)
文章图片
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/16292af70f4c4d0892392d17b61e4a04.jpg)
文章图片
然后在xhr方法中设置headers
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/79cd050e3be34e24a7c92dcf779aeb46.jpg)
文章图片
获取响应数据 需求分析
- 支持Promise链式调用
- 处理返回的数据res,该对象包括服务端返回的数据data、HTTP状态码status、状态消息statusText、响应头headers、请求配置对象config以及请求的XMLHttpRequest对象实例request
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/bc9194e873284e5eb5bdac4c9b16083f.jpg)
文章图片
接下来让我改造xhr方法
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/b49e592904bf4dd3ad6dff3401493085.jpg)
文章图片
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/81090a3f2db54a3a9597140634c618a2.jpg)
文章图片
然后改造axios方法
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/3e72518769804e33b73f329b3eea919a.jpg)
文章图片
![拿起Typescript做一个轮子(三)](https://img.it610.com/image/info8/7442e48c155d4984a95698e67ee75a52.jpg)
文章图片
至此我们axios的基础功能已经实现完了,但目前我们还只实现了正常情况的逻辑,异常情况还没有做处理,那接下就开始对异常情况的处理。
推荐阅读
- 我要做大厨
- 2.6|2.6 Photoshop操作步骤的撤消和重做 [Ps教程]
- 我从来不做坏事
- 子龙老师语录
- 做一件事情的基本原理是什么()
- 做个俗物有什么不好
- 28岁|28岁,做一个通透又自由的姑娘。
- 良心
- 原生家庭之痛与超越
- 我喜欢做菜,是因为懂得了什么是爱