uniapp 里面的 axios, 一个有意思的新插件

对于前端来说, axios 的请求拦截器好处就不用多说了, 但是在uniapp里面编译为小程序平台的时候, 我们就用不了axios, 为什么用不了,因为小程序的网络api和web端还是大相径庭的。这样请求拦截器我们自然就无法使用了.

接下来介绍下 @lylajs/uni-app, 在名字中就可以看的出这个包是 lylajs 里面的子包, 它支持多个平台的使用。还有 @lylajs/qq, @lylajs/wx。直接上图

这个包为什么可以适配出这么多的平台呢?原因就在于有一个可以传入的 adapter, 每个人都可以根据自己的平台实现自己的 adapter 方法。可以在截图看到在创建 lyla 实例的时候可以传入自己的适配器。

github代码

我们拿到数据是不是可以自行实现请求了。当然有一些错误回调规范需要注意,都是一些细节,知道思路就行。

github代码

大致的流程就是,lylajscore 方法会将请求数据,请求方法,请求头等东西规范化,然后传给 adapter

如何使用 @lylajs/uni-app

npm install @lylajs/uni-app

ts 复制代码
import { createLyla } from "@lylajs/uni-app";

const { lyla } = createLyla({
  context: null,
  allowGetBody: true, // 此处是为了适配小程序get请求方法是body
  baseUrl: "https://teacher.hexfuture.net",
  hooks:{
    onAfterResponse: [(res) => {
      return res
    }],
    onBeforeRequest: [(config) => {
      config.headers = {
        ...config.headers,
        _name: 'lyla'
      }
      return config
    }]
  }
})

export {
  lyla
}
html 复制代码
<template>
  <view class="content">
    <image class="logo" src="/static/logo.png"></image>
    <view class="text-area">
      <text class="title">{{ title }}</text>
    </view>
  </view>
</template>

<script>
import { lyla } from '@/utils/request'
export default {
  data() {
    return {
      title: 'Hello',
    }
  },
  onLoad() {
    lyla({
      url: '/lis',
      method: 'GET',
      query: {
        id: 1
      }
    }).then((res) => {
      this.title = res.data
    })
  },
  methods: {},
}
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}

.text-area {
  display: flex;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
}
</style>

常见api封装

ts 复制代码
import { lyla } from "@/utils/request";

type Repo = {
  name: string;
  description: string;
  html_url: string;
}

interface Item {
  id: number;
  category: {
    id: number;
    name: string;
  };
  name: string;
  photoUrls: string[];
  tags: {
    id: number;
    name: string;
  }[];
  status: string;
}

export function getRepoList(data: { status: string }) {
  return lyla<Item>({
    method: 'get',
    url: '/pet/findByStatus',
    query: data
  })
}

感兴趣可以去看看。文档地址

相关推荐
香蕉可乐荷包蛋2 小时前
浅入ES5、ES6(ES2015)、ES2023(ES14)版本对比,及使用建议---ES6就够用(个人觉得)
前端·javascript·es6
未来之窗软件服务2 小时前
资源管理器必要性———仙盟创梦IDE
前端·javascript·ide·仙盟创梦ide
liuyang___3 小时前
第一次经历项目上线
前端·typescript
西哥写代码4 小时前
基于cornerstone3D的dicom影像浏览器 第十八章 自定义序列自动播放条
前端·javascript·vue
清风细雨_林木木4 小时前
Vue 中生成源码映射文件,配置 map
前端·javascript·vue.js
FungLeo4 小时前
node 后端和浏览器前端,有关 RSA 非对称加密的完整实践, 前后端匹配的代码演示
前端·非对称加密·rsa 加密·node 后端
不灭锦鲤4 小时前
xss-labs靶场第11-14关基础详解
前端·xss
不是吧这都有重名5 小时前
利用systemd启动部署在服务器上的web应用
运维·服务器·前端
霸王蟹5 小时前
React中巧妙使用异步组件Suspense优化页面性能。
前端·笔记·学习·react.js·前端框架
Maỿbe5 小时前
利用html制作简历网页和求职信息网页
前端·html