做心悦腾龙光环的网站是什么,湘阴网站建设,域名租赁网站,最专业的车网站建设其实uni-app中内置的uni.request()已经很强大了#xff0c;简单且好用。为了让其更好用#xff0c;同时支持拦截器#xff0c;支持Promise 写法#xff0c;特对其进行封装。同时支持H5和小程序环境#xff0c;更好用啦。文中给出使用示例#xff0c;可以看到使用变得如此… 其实uni-app中内置的uni.request()已经很强大了简单且好用。为了让其更好用同时支持拦截器支持Promise 写法特对其进行封装。同时支持H5和小程序环境更好用啦。文中给出使用示例可以看到使用变得如此简单。在此分享给有需要的小伙伴需要的可以点击收藏。 前言
在uni-app中常见的网络库主要是基于uni-app内置的uni.request()方法这是一个统一的网络请求接口支持HTTP和HTTPS协议可以处理GET、POST等请求方法。这个API提供了基本的HTTP请求功能可以满足大部分应用的网络通信需求。除此之外由于uni-app是基于Vue.js的所以也可以使用一些适用于前端的JavaScript网络库如axios 第三方库支持Promise API有丰富的拦截器、配置选项和错误处理。
为了兼容uni-app生态和微信小程序推荐使用uni-app内置的uni.request()。
原因有以下几点
集成性uni.request()是uni-app框架的一部分与uni-app的其他组件和服务紧密集成使用起来更加方便不需要额外安装和配置。
兼容性uni.request()已经为uni-app的不同平台包括iOS、Android、H5等做了优化和适配可以直接使用而不需要担心跨平台兼容性问题。
简单易用uni.request()的API设计简洁易于理解和使用对于大多数常规的网络请求任务它提供了足够的功能。
性能由于是原生实现uni.request()通常会有更好的性能表现特别是在处理数据量较大或需要高效网络交互的场景。
维护成本使用uni.request()开发者可以专注于业务逻辑而不需要关注网络库的更新和维护。
如果你的项目中已经大量使用了axios或者你需要利用axios提供的特定功能如拦截器、取消请求、超时重试等那么可以考虑继续使用axios。但需要注意的是axios在uni-app中可能需要进行一些适配工作尤其是小程序端。
网络库封装
原始的uni.request使用举例如下
methods(){getSwiperList() { //方法名uni.request({url: 你的数据接口,success: (res) { //如果成功了// 打印数据console.log(res);// 如果请求成功就把数据转存起来方便页面使用this.swipeList res.data.message; },fail: (res) {console.log(请求失败);}})}
}
可以看出虽然简单但是不封装一下还是不够简洁。尤其是不支持Promise写法。
原生态写法太过于繁琐。假如我们一个项目有多个接口那我们每一个接口就要写一个uni.request({})方法而每个方法就要包含url、data、method、header等等这样代码很明显就变得多而杂。而用了Promise写法在编写代码时我们就可以使用async和await写法来简化请求接口代码了。
封装后的使用可以看出多么简单示例如下
// api.js 获取当前正在热映电影
export const getNowHot async (start,count,city) {try {console.log(getNowHot request);const response await uni.$http.post(/movie/in_theaters,{apikey: uni.$apiKey,city:city,start:start,count:count});console.log(response);if (response.statusCode ! 200) {uni.showToast({title: 数据请求失败! ,duration: 1500,icon: none,});return [];}return response.data;} catch (error) {console.error(Network request failed:, error);uni.showToast({title: 网络请求失败! ,duration: 1500,icon: none,});return [];}
};//index.vue 接口调用
mounted() {console.log(mounted)//轮播图接口调用getSwiperList().then(item {this.swiperList item;});//获取豆瓣top250getTop250(0,5).then(item {//this.swiperList item;});// 获取最近热播getNowHot(0,2,郑州).then(result {//this.swiperList item;console.log(getNowHot,result:);console.log(result);});} 上述示例为使用豆瓣影视的接口获取郑州正在热映的电影。豆瓣接口curl测试如下
curl --location --request POST https://api.douban.com/v2/movie/in_theaters?start0count1 --data-urlencode apikeyxxxxxxxxx接口封装
//utils/http.js
class Request {constructor(options {}) {// 请求的根路径this.baseUrl options.baseUrl || // 请求的 url 地址this.url options.url || // 请求方式this.method GET// 请求的参数对象this.data null// header 请求头this.header options.header || {}this.beforeRequest nullthis.afterRequest null}// 添加对header的支持_mergeHeaders(customHeader {}) {return Object.assign({}, this.header, customHeader); // 合并默认header和自定义header}get(url, data {}) {this.method GETthis.url this.baseUrl urlthis.data datareturn this._()}post(url, data {},header {}) {this.method POSTthis.url this.baseUrl urlthis.data datathis.header this._mergeHeaders(header) // 合并headerreturn this._()}put(url, data {}) {this.method PUTthis.url this.baseUrl urlthis.data datareturn this._()}delete(url, data {}) {this.method DELETEthis.url this.baseUrl urlthis.data datareturn this._()}_() {// 清空 header 对象this.header {}// 请求之前做一些事this.beforeRequest typeof this.beforeRequest function this.beforeRequest(this)// 发起请求return new Promise((resolve, reject) {let weixin wx// 适配 uniappif (undefined ! typeof uni) {weixin uni}weixin.request({url: this.url,method: this.method,data: this.data,header: this.header,success: (res) { resolve(res) },fail: (err) { reject(err) },complete: (res) {// 请求完成以后做一些事情this.afterRequest typeof this.afterRequest function this.afterRequest(res)}})})}
}export const $http new Request()
如何使用
在main.js中引入该模块封装并将其挂在全局的uni.$http上即可。如下
import App from ./App
// #ifndef VUE3
import Vue from vue
Vue.config.productionTip false
App.mpType app
const app new Vue({...App
})
app.$mount()
// #endif// #ifdef VUE3
import { createSSRApp } from vue
export function createApp() {const app createSSRApp(App)return {app}
}
// #endifimport { $http } from ./utils/http.js
uni.$http $http
// 配置请求根路径
$http.baseUrl https://api.douban.com/v2
uni.$apiKey xxxxxxxxx
// 请求开始之前做一些事情
$http.beforeRequest function (options) {uni.showLoading({title: 数据加载中...,})
}// 请求完成之后做一些事情
$http.afterRequest function () {uni.hideLoading()
}
在其他文件夹如api文件夹下可以愉快的写接口啦举例如下
// api/home.jsexport const getSwiperList async () {try {console.log(getSwiperList request);const response await uni.$http.get(/api/v1/home/swiperdata);console.log(response.data.list);if (response.statusCode ! 200) {uni.showToast({title: 数据请求失败! ,duration: 1500,icon: none,});return [];}return response.data.list;} catch (error) {console.error(Network request failed:, error);uni.showToast({title: 网络请求失败! ,duration: 1500,icon: none,});return [];}
};export const getTop250 async (start,count) {try {console.log(getTop250 request);const response await uni.$http.post(/movie/top250, {apikey: uni.$apiKey,start:start,count:count},{Content-Type: application/x-www-form-urlencoded});console.log(response);if (response.statusCode ! 200) {uni.showToast({title: 数据请求失败! ,duration: 1500,icon: none,});return [];}return response.data.list;} catch (error) {console.error(Network request failed:, error);uni.showToast({title: 网络请求失败! ,duration: 1500,icon: none,});return [];}
};// 获取当前正在热映电影
export const getNowHot async (start,count,city) {try {console.log(getNowHot request);const response await uni.$http.post(/movie/in_theaters,{apikey: uni.$apiKey,city:city,start:start,count:count});console.log(response);if (response.statusCode ! 200) {uni.showToast({title: 数据请求失败! ,duration: 1500,icon: none,});return [];}return response.data;} catch (error) {console.error(Network request failed:, error);uni.showToast({title: 网络请求失败! ,duration: 1500,icon: none,});return [];}
};
写在最后
最后附上完整的工程项目模版。为了更通用这个是从我的业余项目(爱看电影app小程序) 中抽离出来的工程模版和示例。带网络库的封装和可用的豆瓣影视接口封装以及个人中心页面。可以作为工程模版或小项目练手分享给有需要的小伙伴。
资源下载地址
https://download.csdn.net/download/qq8864/89377440
其他资源
豆瓣接口API使用_热映电影api接口怎么用-CSDN博客
https://feizhaojun.com/?p3813
Movie API Doc | doubanapi
uniapp 请求解决跨域问题_uniapp跨域请求-CSDN博客
豆瓣API常用api总结实例_douban api-CSDN博客
组件使用的入门教程 | uni-app官网
微信小程序 --- wx.request网络请求封装-CSDN博客