js适配器模式

适配器模式通过把一个类的接口变换成客户端所期待的另一种接口 ,可以帮我们解决不兼容的问题。

应用

js 复制代码
// Ajax适配器函数,入参与旧接口保持一致
async function AjaxAdapter(type, url, data, success, failed) {
    const type = type.toUpperCase()
    let result
    try {
         // 实际的请求全部由新接口发起
         if(type === 'GET') {
            result = await HttpUtils.get(url) || {}
        } else if(type === 'POST') {
            result = await HttpUtils.post(url, data) || {}
        }
        // 假设请求成功对应的状态码是1
        result.statusCode === 1 && success ? success(result) : failed(result.statusCode)
    } catch(error) {
        // 捕捉网络错误
        if(failed){
            failed(error.statusCode);
        }
    }
}

// 用适配器适配旧的Ajax方法
async function Ajax(type, url, data, success, failed) {
    await AjaxAdapter(type, url, data, success, failed)
}

axios中的适配器

在axios中,适配器模式是通过adapter函数来实现的。adapter函数是一个高阶函数,它接受一个config对象作为参数,并返回一个新的config对象。

adapter函数中,可以对config对象进行修改和扩展,以适应不同的环境和需求。

例如,可以在adapter函数中添加请求拦截器和响应拦截器,以实现对请求和响应的统一处理。 同时,adapter函数还可以根据不同的环境和需求,选择不同的适配器来处理请求。

例如,在浏览器环境中,可以使用XMLHttpRequest适配器来发送请求;

在Node.js环境中,可以使用http适配器来发送请求。 具体来说,axios中的适配器模式实现了以下功能:

  1. 请求拦截器:在发送请求之前,可以对请求进行拦截和处理。例如,可以在请求拦截器中添加请求头、修改请求参数等。
  2. 响应拦截器:在接收到响应之后,可以对响应进行拦截和处理。例如,可以在响应拦截器中解析响应数据、处理错误信息等。
  3. 适配器选择:根据不同的环境和需求,选择不同的适配器来处理请求。例如,在浏览器环境中,可以使用XMLHttpRequest适配器来发送请求;在Node.js环境中,可以使用http适配器来发送请求。
  4. 请求发送:根据选择的适配器,发送请求并返回响应。 通过这种方式,axios可以实现对不同环境和需求的适配,同时也可以提高代码的可维护性和可扩展性。
js 复制代码
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  })   
     
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });   

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
})
复制代码
相关推荐
csj501 天前
安卓基础之《(13)—数据存储(3)存储卡的文件操作》
android
冬奇Lab1 天前
Android车机代驾模式黑屏之谜:一次STR唤醒问题的深度剖析
android·性能优化·debug
2501_916008891 天前
在 Windows 上使用开心上架(Appuploader)在 Windows 环境下创建与管理 iOS 证书
android·ios·小程序·https·uni-app·iphone·webview
叶羽西1 天前
Android15 框架层Java代码中的各种打印接口
android
恋猫de小郭1 天前
Dart 官方再解释为什么放弃了宏编程,并转向优化 build_runner ? 和 Kotlin 的区别又是什么?
android·前端·flutter
Kapaseker1 天前
淘一淘七载征途 技术深耕守本初
android·kotlin
小陈phd1 天前
大语言模型实战(十一)——基于MAI-UI-8B 实现 Android UI 自动化:从元素定位到多步导航
android·ui·自动化
赛恩斯1 天前
Android 13源码下载
android
_李小白1 天前
【Android 性能分析】第三天:Android Studio Profiler
android·stm32·android studio