马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
一、JavaScript XHR、Fetch
AJAX:一种在无需重新加载整个网页的环境下,可以或许更新部分网页的技能。在配景与服务器举行少量数据交换,Ajax 可以使网页实现异步更新。在不重新加载整个网页的环境下,对网页的某部分举行更新
Fetch:基于 promise 计划的。Fetch 的代码布局比起 ajax 简单多。fetch 不是 ajax 的进一步封装,而是原生 js,没有使用 XMLHttpRequest 对象
1.1 前端数据哀求方式
- 后端:服务器端
- 服务器端渲染 SSR(后端渲染):全部都是后端开辟的
- 客户端发送哀求
- 服务端吸收哀求并使用 jsp/asp/php 返回相应 HTML 文档
- 页面革新,客户端加载新的HTML文档
- SSR 的缺点
- 页面本质上只有一些数据发生了变革,而服务器却要重绘整个页面,违背了 DRY(Don’t repeat yourself)原则
- 给网络带宽带来不须要的开销
- 前后端分离(客户端渲染、前端渲染)
- 后端只必要关心 API 服务器(提供数据的服务器)和数据库
- AJAX:
- 在不重新革新网页的环境下与服务器通讯,交换数据,或更新页面(无页面革新获取服务器数据的技能)
- 吸收并使用从服务器发来的数据
- 异步的 JavaScript 和 XML(不消了,现在使用 Json)
1.2 HTTP
- 超文本传输协议:用于分布式、协作式和超媒体信息体系的应用层协议
- 最早是为了吸收 html 页面,欣赏器举行渲染
- http 是一个客户端和服务端之间哀求和相应的尺度
- 通过 HPPT 大概 HTTPS( http上增长的一个安全层)协议哀求的资源由同一资源标识符 URL 来标识
- 通过使用网页欣赏器、网络爬虫大概别的的工具,客户端发起一个HTTP哀求到服务器上指定端口(默认端口为80)
- 相应的服务器上存储着一些资源,好比 HTML文件和图像
- 这个相应服务器为源服务器(origin server)
- http 就是和服务器沟通的一种协议:哀求对象、相应对象
- 网页中的资源通常是被放在 web 资源服务器中,由欣赏器主动发送 http 哀求来获取、剖析、展示的
1.3 网页中资源的获取
- 网页中的资源通常是被放在 Web 资源服务器中,由欣赏器主动发送 HTTP 哀求来获取、剖析、展示的
- **页面中许多数据是动态展示的:**页面中的数据展示、搜刮数据、表单验证等等,也是通过在 JavaScript 中发送 HTTP 哀求获取的
1.4 HTTP 的构成
- 一次 http 哀求重要包罗:哀求和相应
- 哀求
- 哀求行:方法(哀求方式)、URL、协议版本(现在采取的是什么版本)
- 哀求头:客户端会默认转达过来一些信息
- content-type:哀求携带的数据范例(告诉服务器现在传送的数据以什么情势传已往)
- application/x-www-form-urlencoded:以&分隔的键值对(以=分隔)
- application/json:{“”:“”}json范例
- text/plain:平凡文本 ×
- application/xml:少用,xml范例
- <xml>
- <name>lili</name>
- </xml>
复制代码
- multipart/form-data:上传文件,许多时间不必要手动设置
- content-length:文件的巨细长度
- keep-alive:不立刻断开,继承保持毗连一会儿
- node 开辟服务器:保持五秒
- http1.1 默认开启了
- acept-encoding(吸收的客户端):告知服务器,客户端支持吸收的文件的压缩格式
- zip/rar/7z
- gzip(给你返回更小的压缩文件)
- accept:我(客户端)可以或许吸收的文件格式(一样寻常为 json)
- user-agent:客户端相干的信息
- 相应
- 相应行:协议版本、状态码、状态码的缘故起因短语
- 200 OK 哀求乐成
- 201 Created POST哀求,创建新的资源
- 301 哀求资源的URL已经修改,重定向
- 大于四百:错误
- 400 客户端的错误
- 401 未授权的错误
- 403 客户端没有权限访问
- 404 服务器找不到哀求的资源
- 500 服务器错误,服务器不知道怎样处置惩罚
- 503 服务器不可用
- 相应头
- 拿到相应数据:xhr.response
- 可以设置吸收的范例:xhr.responseType="json"默认是text
- 相应体
1.5 HTTP 的版本
- HTTP/0.9 版本:1991年,只支持 get 哀求方法获取文本数据
- HTTP/1.0:TCP毗连
- HTTP/1.1(使用最广泛)
- 发布于1997年
- 增长了PUT、DELETE等哀求方法
- 采取长期毗连(Connection: keep-alive),多个哀求可以共用同一个 TCP 毗连
- HTTP/2.0
- HTTP/3.0
1.6 HTTP 的哀求方式
- 发送一次哀求怎样同服务器举行沟通
- RFC(版本规范)中界说了一组哀求方式,标识要对给定资源实验的操纵
- GET:哀求数据,获取数据
- HEAD:返回的数据没有相应体
- POST:提交数据
- PUT:更换目标资源
- DELETE:删除数据
- PATCH:修改数据
- CONNECT:署理服务器
- TRACE:消息环回测试
1.7 AJAX 发送哀求
- 第一种方式
- 创建 XMLHttpRequest 对象
- 监听状态的改变(宏使命)
- 一次网络哀求中状态发生了许多次变革,数字表近况态
- 0(不监听):署理被创建
- 1 (open):open 方法已经被调用
- 2(send):send 方法已经被调用,而且头部和状态已经可得到
- 3(下载中)
- 4:DONE 已完成
- 这个状态并非是 HTTP 的相应状态,而是记载的 XMLHttpRequest 对象的状态变革:http 相应状态通过 status 获取
- **发送同步哀求:**将 open 的第三个参数设置为 false
- 发送哀求(欣赏器资助发送对应的哀求):现实开辟使用异步哀求,不会壅闭js代码继承实验: xhr.open("get", "http://123.207.32.32:8000/home/multidata", false)
- 除了 onreadystatechange 另有其他的事故可以监听
- loadstart:哀求开始
- progress:文件上传
- abort:取消了哀求
- load:哀求乐成完成
- loadend
- error:发生毗连错误
- onload:只调用一次
- timeout:哀求超时
- 设置哀求
- open方法来设置,参数如下:
- method:哀求的方式
- URL:哀求的所在
- json 范例的接口(90%)
- text 范例的接口
- xml 范例的接口
- // 1.
- const xhr = new XMLHttpRequest()
- // 2.onload监听数据加载完成
- xhr.onload = function() {
- // const resJSON = JSON.parse(xhr.response)
- console.log(xhr.response)
- // console.log(xhr.responseText)
- // console.log(xhr.responseXML)
- }
- // 3.告知xhr获取到的数据的类型
- xhr.responseType = "json"
- // xhr.responseType = "xml"
- // 4.配置网络请求
- // 4.1.json类型的接口
- xhr.open("get", "http://xxxxx")
- // 4.2.json类型的接口
- // xhr.open("get", "http://xxxxx/hello_json")
- // 4.3.text类型的接口
- // xhr.open("get", "http://xxxxx/hello_text")
- // 4.4.xml类型的接口
- // xhr.open("get", "xxxxx/hello_xml")
- // 5.发送网络请求
- xhr.send()
复制代码
- <script>
- // xhr四步骤:
- // 1. 创建XMLHttpRequest对象
- // 所有的东西都放在了 xhr 里面
- const xhr = new XMLHttpRequest()
- // 2. 监听状态的改变(宏任务)
- xhr.onreadystatechange=function(){
- if(xhr.readyState!==XMLHttpRequest.DONE)return
- // 2.1将字符串转成JSON对象
- // const resJSON=JSON.parse(xhr.response)
- // const banners=resJSON.data.banner
- log(xhr.response)
- }
- // 告知xhr获取到的数据的类型,默认设置为text
- xhr.responseType="json"
- // 3. 调用open方法进行配置
- //open第三个参数boolean表示同步或者异步,默认true异步
- xhr.open("get","https://www.baidu.com",false)
-
- // 4. 调用send发送请求
- xhr.send()
- </script>
复制代码 1.8 获取 http 的状态码
- 前面都是记载 xhr 对象本身的状态变革,并非针对 http 的网络哀求状态,http 网络哀求的状态必要通过 .status 获取
-
- // 1.创建对象
- const xhr = new XMLHttpRequest()
- // 2.监听结果
- xhr.onload = function() {
- console.log(xhr.status, xhr.statusText)
- // 根据http的状态码判断是否请求成功
- if (xhr.status >= 200 && xhr.status < 300) {
- console.log(xhr.response)
- } else {
- console.log(xhr.status, xhr.statusText)
- }
- }
- xhr.onerror = function() {
- console.log("onerror", xhr.status, xhr.statusText)
- }
- // 3.设置响应类型
- xhr.responseType = "json"
- // 4.配置网络请求
- // xhr.open("get", "http://xxxxx/abc/cba/aaa")
- xhr.open("get", "http://xxxxx/home/multidata")
- // 5.发送网络请求
- xhr.send()
复制代码 1.9 Get、Post 哀求传参
- 要不要转达数据取决于接口需不必要数据
- url
- 常见的转达给服务器数据的方式有如下几种:
- 方式一:GET 哀求的 query 参数
- 缺点:以明文的情势直接放在对应的 URL,属于 URL 的一部分,没有那么安全;而 post 哀求转达参数的方式有许多种
- 方式二:POST 哀求 x-www-form-urlencoded 格式
- 方式三:POST 哀求 FormData 格式
- 方式四:POST 哀求 JSON 格式
- const formEl = document.querySelector(".info")
- const sendBtn = document.querySelector(".send")
- sendBtn.onclick = function() {
- // 创建xhr对象
- const xhr = new XMLHttpRequest()
- // 监听数据响应
- xhr.onload = function() {
- console.log(xhr.response)
- }
- // 配置请求
- xhr.responseType = "json"
- // 1.传递参数方式一: get -> query
- // xhr.open("get", "http://xxxx/get?name=lili&age=18&address=广州市")
- // 2.传递参数方式二: post -> urlencoded
- // xhr.open("post", "http://xxxx/posturl")
- // // 发送请求(请求体body)
- // xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
- // xhr.send("name=lili&age=18&address=广州市")
- // 3.传递参数方式三: post -> formdata
- // xhr.open("post", "http://xxxx/postform")
- // 得将元素转成 form 对象
- // // formElement对象转成FormData对象
- // const formData = new FormData(formEl)
- // xhr.send(formData)
- // 4.传递参数方式四: post -> json
- xhr.open("post", "http://xxx/postjson")
- xhr.setRequestHeader("Content-type", "application/json")
- xhr.send(JSON.stringify({name: "lili", age: 18, height: 1.88}))
- }
-
复制代码 1.10 ajax 网络哀求封装
- function liliajax({
- url,
- method = "get",
- data = {},
- headers = {}, // token
- success,
- failure
- } = {}) {
- // 1.创建对象
- const xhr = new XMLHttpRequest()
- // 2.监听数据
- xhr.onload = function() {
- if (xhr.status >= 200 && xhr.status < 300) {
- success && success(xhr.response)
- } else {
- failure && failure({ status: xhr.status, message: xhr.statusText })
- }
- }
- // 3.设置类型
- xhr.responseType = "json"
- // 4.open方法
- // 一般不推荐写在 data 里面
- if (method.toUpperCase() === "GET") {
- // 对 data 进行遍历
- const queryStrings = []
- for (const key in data) {
- queryStrings.push(`${key}=${data[key]}`)
- }
- url = url + "?" + queryStrings.join("&")
- xhr.open(method, url)
- xhr.send()
- } else {
- xhr.open(method, url)
- xhr.setRequestHeader("Content-type", "application/json")
- xhr.send(JSON.stringify(data))
- }
- return xhr
- }
- // 调用者
- liliajax({
- url: "http://xxx/get",
- method: "GET",
- data: {
- name: "lili",
- age: 18
- },
- success: function(res) {
- console.log("res:", res)
- },
- failure: function(err) {
- // alert(err.message)
- }
- })
- // liliajax({
- // url: "http://xxxx/postjson",
- // method: "post",
- // data: {
- // name: "jsondata",
- // age: 22
- // },
- // success: function(res) {
- // console.log("res:", res)
- // },
- // failure: function(err) {
- // // alert(err.message)
- // }
- // })
复制代码- function liliajax({
- url,
- method = "get",
- data = {},
- timeout = 10000,
- headers = {}, // token
- } = {}) {
- // 1.创建对象
- const xhr = new XMLHttpRequest()
- // 2.创建Promise
- const promise = new Promise((resolve, reject) => {
- // 2.监听数据
- xhr.onload = function() {
- if (xhr.status >= 200 && xhr.status < 300) {
- resolve(xhr.response)
- } else {
- reject({ status: xhr.status, message: xhr.statusText })
- }
- }
- // 3.设置类型
- xhr.responseType = "json"
- xhr.timeout = timeout
- // 4.open方法
- if (method.toUpperCase() === "GET") {
- const queryStrings = []
- for (const key in data) {
- queryStrings.push(`${key}=${data[key]}`)
- }
- url = url + "?" + queryStrings.join("&")
- xhr.open(method, url)
- xhr.send()
- } else {
- xhr.open(method, url)
- xhr.setRequestHeader("Content-type", "application/json")
- xhr.send(JSON.stringify(data))
- }
- })
- promise.xhr = xhr
- return promise
- }
复制代码- const promise = liliajax({
- url: "http://xxxx/get",
- data: {
- username: "lili",
- password: "123456"
- }
- })
- promise.then(res => {
- console.log("res:", res)
- }).catch(err => {
- console.log("err:", err)
- })
复制代码 1.11 timeout、手动取消哀求
- timeout 欣赏器到达逾期时间还没有获取对应的结果,取消本次哀求
- 可以通过 abort 方法欺压取消哀求
- <button>取消请求</button>
- <script>
- const xhr = new XMLHttpRequest()
- xhr.onload = function() {
- console.log(xhr.response)
- }
- xhr.onabort = function() {
- console.log("请求被取消掉了")
- }
-
- xhr.responseType = "json"
- // 1.超市时间的设置
- xhr.ontimeout = function() {
- console.log("请求过期: timeout")
- }
- // timeout: 浏览器达到过期时间还没有获取到对应的结果时, 取消本次请求
- // xhr.timeout = 3000
- xhr.open("get", "http://xxxxx/timeout")
- xhr.send()
- // 2.手动取消结果
- const cancelBtn = document.querySelector("button")
- cancelBtn.onclick = function() {
- xhr.abort()
- }
- </script>
复制代码 1.12 熟悉 Fetch 和 Fetch API 发送网络哀求
- fetch 是 xhr 的代替方案,提供了更加今世的处置惩罚方案
- 返回值是一个 Promise
- 在哀求发送乐成时,调用 resolve 回调 then
- 在哀求发送失败时,调用 reject 回调 catch
- 全部的操纵并不是都在一个对象上面
- fetch 函数的使用
- 参数
- input
- 界说要获取的资源所在,可以是一个 URL 字符串,也可以使用一个 Request 对象(实验性特性)范例
- init:其他初始化参数
- method: 哀求使用的方法,如 GET、POST
- headers: 哀求的头信息
- body: 哀求的 body 信息
- // 1.fetch发送get请求
- // 1.1.未优化的代码
- // fetch("xxxx").then(res => {
- // // 1.获取到response
- // const response = res
- // // 2.获取具体的结果
- // response.json().then(res => {
- // console.log("res:", res)
- // })
- // }).catch(err => {
- // console.log("err:", err)
- // })
- // 1.2. 优化方式一:
- // fetch("xxxx").then(res => {
- // // 1.获取到response
- // const response = res
- // // 2.获取具体的结果
- // return response.json()
- // }).then(res => {
- // console.log("res:", res)
- // }).catch(err => {
- // console.log("err:", err)
- // })
- // 1.3. 优化方式二:
- // async function getData() {
- // const response = await fetch("http://xxxxx")
- // const res = await response.json()
- // console.log("res:", res)
- // }
- // getData()
- // 2.post请求并且有参数
- async function getData() {
- // const response = await fetch("http://xxxxx/postjson", {
- // method: "post",
- // // headers: {
- // // "Content-type": "application/json"
- // // },
- // body: JSON.stringify({
- // name: "lili",
- // age: 18
- // })
- // })
-
- const formData = new FormData()
- formData.append("name", "lili")
- formData.append("age", 18)
- const response = await fetch("http://xxxx/postform", {
- method: "post",
- body: formData
- })
- // 获取response状态
- console.log(response.ok, response.status, response.statusText)
- const res = await response.json()
- console.log("res:", res)
- }
- getData()
复制代码 1.13 XMLHttpRequest 文件上传
- 文件上传:头像上传、照片等
- 通过表单传给服务器
- 可以检察上传的进度
- <input class="file" type="file">
- <button class="upload">上传文件</button>
-
- <script>
- // xhr/fetch
- const uploadBtn = document.querySelector(".upload")
- uploadBtn.onclick = function() {
- // 1.创建对象
- const xhr = new XMLHttpRequest()
- // 2.监听结果
- xhr.onload = function() {
- console.log(xhr.response)
- }
- xhr.onprogress = function(event) {
- console.log(event)
- }
-
- xhr.responseType = "json"
- xhr.open("post", "http://xxxxx/upload")
- // 表单
- const fileEl = document.querySelector(".file")
- const file = fileEl.files[0]
- const formData = new FormData()
- formData.append("avatar", file)
- xhr.send(formData)
- }
- </script>
复制代码 1.14 Fetch 哀求文件上传
- <input class="file" type="file">
- <button class="upload">上传文件</button>
-
- <script>
- // xhr/fetch
- const uploadBtn = document.querySelector(".upload")
- uploadBtn.onclick = async function() {
- // 表单
- const fileEl = document.querySelector(".file")
- const file = fileEl.files[0]
- const formData = new FormData()
- formData.append("avatar", file)
- // 发送fetch请求
- const response = await fetch("http://xxxx/upload", {
- method: "post",
- body: formData
- })
- const res = await response.json()
- console.log("res:", res)
- }
- </script>
复制代码 二、网络哀求库 - axios
Axios:是一种基于 Promise 封装的 HTTP 客户端。
特点如下:
- 欣赏器端发起 XMLHttpRequests 哀求
- node 端发起 http 哀求
- 支持 Promise API
- 监听哀求和返回
- 对哀求和返回举行转化
- 取消哀求
- 主动转换 json 数据
- 客户端支持反抗 XSRF 攻击
2.1 axios
- 功能特点
- 在欣赏器中发送 XMLHttpRequests 哀求
- 在 node.js 中发送 http 哀求
- 支持 Promise API
- 拦截哀求和相应
- 转换哀求和相应数据
- axios: ajax i/o system
2.2 常见设置选项
- 哀求所在:url: ‘/user’,
- 哀求范例:method: ‘get’,
- 请根路径:baseURL: ‘http://www.xxx.com/api’,
- 哀求前的数据处置惩罚:transformRequest:[function(data){}],
- 哀求后的数据处置惩罚:transformResponse: [function(data){}],
- 自界说的哀求头:headers:{‘x-Requested-With’:‘XMLHttpRequest’},
- URL查询对象:params:{ id: 12 },
- 查询对象序列化函数:paramsSerializer: function(params){ }
- request body:data: { key: ‘aa’},
- 超时设置:timeout: 1000,
- import { createApp } from "vue";
- import App from "./App.vue";
- import axios from "axios";
- createApp(App).mount("#app");
- // 1. baseURL
- const baseURL = "http://xxxxx:8000"
- // 给axios实例配置公共的基础配置
- axios.defaults.baseURL = baseURL
- axios.defaults.baseURL = 10000
- axios.defaults.headers = {}
- // 1.1 get:
- axios.get("/home/multidata").then(res => {
- console.log(res.data);
- })
- // 1.2 get
复制代码 2.3 axios 哀求方式
- 支持多种哀求方式
- axios(config)
- axios.request(config)
- axios.get(url[, config])
- axios.delete(url[, config])
- axios.head(url[, config])
- axios.post(url[, data[, config]])
- axios.put(url[, data[, config]])
- axios.patch(url[, data[, config]])
- import { createApp } from "vue";
- import App from "./App.vue";
- import axios from "axios";
- createApp(App).mount("#app");
- //1. 发送 request请求:发送一些配置
- axios
- .request({
- url: "http://xxxxx",
- method: "get",
- })
- .then((res) => {
- console.log(res.data);
- });
- // 2. 发送get请求:
- // 传递参数:
- // 2.1 querry参数
- axios.get("http:/xxxxx/lyric?id=500665346", {}).then((res) => {
- console.log(res.data);
- });
- // 2.2 params这个使用比较多
- axios
- .get("http://xxxxx/lyric", {
- params: {
- id: 500665346,
- },
- })
- .then((res) => {
- console.log(res.data);
- });
- // 3. 发送 post 请求:post请求的 url 参数是不能拼接到后面的,只能放在请求体里面
- // 两种写法
- axios
- .post("http://xxxxx/postjson", {
- username: "lili",
- password: "123455",
- })
- .then((res) => {
- console.log(res.data);
- });
- axios
- .post("http://xxxxx/postjson", {
- data: {
- username: "lili",
- password: "123455",
- },
- })
- .then((res) => {
- console.log(res.data);
- });
复制代码
- 同时发送两个哀求
- 使用 axios.all, 可以放入多个哀求的数组
- axios.all([]) 返回的结果是一个数组,使用 axios.spread 可将数组 [res1,res2] 睁开为 res1, res2
- // 2. axios 发送多个请求
- // Promise.all
- axios.all([
- axios.get("/xxx/multidata"),
- axios.get("/xxx/multidata2")
- ]).then(res => {
- console.log(res.data);
- })
复制代码 2.4 axios 创建实例
- 对于单独的 url 会创建单独的实例
- 看开辟过程中有多少个实例
- import { createApp } from "vue";
- import App from "./App.vue";
- import axios from "axios";
- createApp(App).mount("#app");
- // axios 默认库提供给我们的实例对象
- axios.get("http://xxxxx/lyric?id=500665346");
- // 创建其他的实例发送网络请求
- const instance1 = axios.create({
- baseURL: "http://xxxx",
- timeout: 6000,
- headers: {},
- });
- instance1.get("/lyric", {
- params: {
- id: 500665346,
- },
- });
- const instance2 = axios.create({
- baseURL: "http://xxxxx",
- timeout: 9000,
- headers: {},
- });
复制代码 2.5 哀求和相应拦截器
- 在发出网络哀求之前
- 哀求乐成
- 表现 loading 动画
- 对原来的设置文件举行修改
- header
- 认证登岸:传入 token、cookie
- 对哀求参数举行某些转化
- 在得到相应结果之前
- 相应乐成
- 竣事 loading 动画
- 对数据举行转化,再返回数据
- 举行处置惩罚
- // 对实例配置拦截器
- axios.interceptors.request.use(请求成功回调拦截, 请求失败回调拦截);
- // 一般都不会请求失败
- axios.interceptors.request.use(
- (config) => {
- if (config.url === "user/info") config.headers["token"] = "lili";
- // 请求成功的拦截
- return config;
- },
- (err) => {
- console.log("请求失败的拦截,基本上不会发生");
- }
- );
- // 400 404 请求失败
- axios.interceptors.response.use(成功回调, 失败回调);
- axios.interceptors.response.use(
- (res) => {
- // 这里对响应的结果进行转化
- // 在得到结果的时候就不需要 res.data 了
- // 响应成功的拦截
- return res.data;
- },
- (err) => {
- // 响应失败的拦截
- return err;
- }
- );
- axios
- .get("http://xxxxx/lyric?id=500665346")
- .then((res) => {
- console.log(res);
- })
- .catch((err) => {
- console.log(err);
- });
复制代码 2.6 封装
- import axios from "axios";
- class LiliRequest {
- constructor(baseURL, timeout = 10000) {
- // 创建一个实例进行配置
- this.instance = axios.create({
- baseURL,
- timeout
- })
- }
- request(config) {
- return new Promise((resolve, reject) => {
- this.instance
- .request(config)
- .then((res) => {
- resolve(res.data);
- })
- .catch((err) => {
- reject(err);
- });
- });
- }
- get(config) {
- return this.request({ ...config, method: "get" });
- }
- post(config) {
- return this.request({ ...config, method: "post" });
- }
- }
- const liliRequest1 = new LiliRequest("http://www.baidu.com")
- const liliRequest2 = new LiliRequest("http://www.taobao.com")
- export default new LiliRequest()
复制代码- import liliRequest from './service/index'
复制代码 三、TypeScript - axios 封装
3.1 根本封装
- import axios from "axios";
- import type { AxiosInstance, AxiosRequestConfig } from "axios";
- class LiliRequest {
- instance: AxiosInstance;
- // 1. 创建实例
- // request 实例 => axios实例
- constructor(config: AxiosRequestConfig) {
- this.instance = axios.create(config);
- }
-
- // 2. 封装网络请求的方法
- request(config: AxiosRequestConfig) {
- return this.instance.request(config)
- }
- get() { }
-
- }
- export default LiliRequest;
复制代码 拦截器
- import axios from "axios";
- import type { AxiosInstance, AxiosRequestConfig } from "axios";
- // 拦截器:蒙版 loading/token/修改配置
- class LiliRequest {
- instance: AxiosInstance;
- // 1. 创建实例
- // request 实例 => axios实例
- constructor(config: AxiosRequestConfig) {
- this.instance = axios.create(config);
- // 每个instance实例都添加拦截器
- // 传入一个config对config进行修改再返回
- this.instance.interceptors.request.use(
- (config) => {
- // loading/token
- console.log("全局请求成功的拦截");
- return config;
- },
- (err) => {
- console.log("全局请求失败的拦截");
- return err;
- }
- );
- this.instance.interceptors.response.use(
- (res) => {
- console.log("全局响应成功的拦截");
- return res;
- },
- (err) => {
- console.log("全局响应失败的拦截");
- return err;
- }
- );
- }
- // 2. 封装网络请求的方法
- request(config: AxiosRequestConfig) {
- return this.instance.request(config);
- }
- get() {}
- }
- export default LiliRequest;
复制代码- import axios from "axios";
- import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from "axios";
- // 拦截器:蒙版 loading/token/修改配置
- import type { LILIInterceptors, LiliRequestConfig } from "./type";
- class LiliRequest {
- instance: AxiosInstance;
- // 1. 创建实例
- // request 实例 => axios实例
- constructor(config: LiliRequestConfig) {
- this.instance = axios.create(config);
- // 每个instance实例都添加拦截器
- // 传入一个config对config进行修改再返回
- this.instance.interceptors.request.use(
- (config) => {
- // loading/token
- console.log("全局请求成功的拦截");
- return config;
- },
- (err) => {
- console.log("全局请求失败的拦截");
- return err;
- }
- );
- this.instance.interceptors.response.use(
- (res) => {
- console.log("全局响应成功的拦截");
- return res;
- },
- (err) => {
- console.log("全局响应失败的拦截");
- return err;
- }
- );
- // 同时存在不存在覆盖
- // 判断请求是否添加拦截器,针对每一个请求做精细化处理
- // 针对特定的liliRequest实例添加拦截器
- // if (config.interceptors) {//类型缩小
- this.instance.interceptors.request.use(config.interceptors?.requestSuccessFn, config.interceptors?.requestFailureFn);
- this.instance.interceptors.response.use(config.interceptors?.responseSuccessFn, config.interceptors?.responseFailureFn);
- // }
- }
- // 2. 封装网络请求的方法
- request(config: AxiosRequestConfig) {
- return this.instance.request(config);
- }
- get() {}
- }
- export default LiliRequest;
复制代码
- LiliRequest 类单次哀求:针对差异的需求创建差异的拦截
- import axios from "axios";
- import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from "axios";
- // 拦截器:蒙版 loading/token/修改配置
- import type { LILIInterceptors, LiliRequestConfig } from "./type";
- class LiliRequest {
- instance: AxiosInstance;
- // 1. 创建实例
- // request 实例 => axios实例
- constructor(config: LiliRequestConfig) {
- this.instance = axios.create(config);
- // 每个instance实例都添加拦截器
- // 传入一个config对config进行修改再返回
- this.instance.interceptors.request.use(
- (config) => {
- // loading/token
- console.log("全局请求成功的拦截");
- return config;
- },
- (err) => {
- console.log("全局请求失败的拦截");
- return err;
- }
- );
- this.instance.interceptors.response.use(
- (res) => {
- console.log("全局响应成功的拦截");
- return res;
- },
- (err) => {
- console.log("全局响应失败的拦截");
- return err;
- }
- );
- // 同时存在不存在覆盖
- // 判断请求是否添加拦截器,针对每一个请求做精细化处理
- // 针对特定的liliRequest实例添加拦截器
- // if (config.interceptors) {//类型缩小
- this.instance.interceptors.request.use(config.interceptors?.requestSuccessFn, config.interceptors?.requestFailureFn);
- this.instance.interceptors.response.use(config.interceptors?.responseSuccessFn, config.interceptors?.responseFailureFn);
- // }
- }
- // 2. 封装网络请求的方法
- request(config: LiliRequestConfig) {
- // 拦截器的本质是一些钩子函数,对其进行回调
- if (config.interceptors?.requestSuccessFn) {
- config = config.interceptors.requestSuccessFn(config);
- }
- return new Promise((resolve, reject) => {
- this.instance
- .request(config)
- .then((res) => {
- if (config.interceptors?.responseSuccessFn) {
- res = config.interceptors.responseSuccessFn(res);
- }
- resolve(res);
- })
- .catch((err) => {
- reject(err);
- });
- });
- }
- get() {}
- }
- export default LiliRequest;
复制代码 3.2 返回结果的范例处置惩罚
- import liliRequest from "..";
- interface IHmoeData{
- data: any,
- returnCode: string,
- success:boolean
- }
- liliRequest.request<IHmoeData>({
- url:"/user/name"
- }).then(res => {
- console.log(res);
-
- })
复制代码- // 2. 封装网络请求的方法
- request<T=any>(config: LiliRequestConfig) {
- // 拦截器的本质是一些钩子函数,对其进行回调
- if (config.interceptors?.requestSuccessFn) {
- config = config.interceptors.requestSuccessFn(config);
- }
- return new Promise<T>((resolve, reject) => {
- this.instance
- .request<any,T>(config)
- .then((res) => {
- if (config.interceptors?.responseSuccessFn) {
- // res = config.interceptors.responseSuccessFn(res);
- }
- resolve(res);
- })
- .catch((err) => {
- reject(err);
- });
- });
- }
复制代码 3.3 接口范例中的泛型处置惩罚
- import axios from "axios";
- import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from "axios";
- // 拦截器:蒙版 loading/token/修改配置
- import type { LILIInterceptors, LiliRequestConfig } from "./type";
- class LiliRequest {
- instance: AxiosInstance;
- // 1. 创建实例
- // request 实例 => axios实例
- constructor(config: LiliRequestConfig) {
- this.instance = axios.create(config);
- // 每个instance实例都添加拦截器
- // 传入一个config对config进行修改再返回
- this.instance.interceptors.request.use(
- (config) => {
- // loading/token
- console.log("全局请求成功的拦截");
- return config;
- },
- (err) => {
- console.log("全局请求失败的拦截");
- return err;
- }
- );
- this.instance.interceptors.response.use(
- (res) => {
- console.log("全局响应成功的拦截");
- return res.data;
- },
- (err) => {
- console.log("全局响应失败的拦截");
- return err;
- }
- );
- // 同时存在不存在覆盖
- // 判断请求是否添加拦截器,针对每一个请求做精细化处理
- // 针对特定的liliRequest实例添加拦截器
- // if (config.interceptors) {//类型缩小
- this.instance.interceptors.request.use(config.interceptors?.requestSuccessFn, config.interceptors?.requestFailureFn);
- this.instance.interceptors.response.use(config.interceptors?.responseSuccessFn, config.interceptors?.responseFailureFn);
- // }
- }
- // 2. 封装网络请求的方法
- request<T=any>(config: LiliRequestConfig<T>) {
- // 拦截器的本质是一些钩子函数,对其进行回调
- if (config.interceptors?.requestSuccessFn) {
- config = config.interceptors.requestSuccessFn(config);
- }
- return new Promise<T>((resolve, reject) => {
- this.instance
- .request<any,T>(config)
- .then((res) => {
- if (config.interceptors?.responseSuccessFn) {
- // res = config.interceptors.responseSuccessFn(res);
- }
- resolve(res);
- })
- .catch((err) => {
- reject(err);
- });
- });
- }
- get() {}
- }
- export default LiliRequest;
复制代码- import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from "axios";
- // 针对AxiosRequestConfig配置进行扩展
- export interface LILIInterceptors<T=AxiosResponse> {
- requestSuccessFn?: (config: AxiosRequestConfig) => AxiosRequestConfig;
- requestFailureFn?: (err: any) => any;
- responseSuccessFn?: (res: T) => T;
- responseFailureFn?: (err: any) => any;
- }
- export interface LiliRequestConfig<T=AxiosResponse> extends AxiosRequestConfig {
- interceptors?: LILIInterceptors<T>;
- }
复制代码 3.4 添加其他哀求方式
- get<T = any>(config: LiliRequestConfig<T>) {
- return this.request({...config,method:"GET"})
- }
- post<T = any>(config: LiliRequestConfig<T>) {
- return this.request({...config,method:"POST"})
- }
- delete<T = any>(config: LiliRequestConfig<T>) {
- return this.request({...config,method:"DELETE"})
- }
- patch<T = any>(config: LiliRequestConfig<T>) {
- return this.request({...config,method:"PATCH"})
- }
复制代码 3.5 总结
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金 |