vue封装sdk(uview2.0封装http请求实战以及常见请求传参实录)
导读: 1.前言...
1.前言
2.使用步骤
2.1 配置请求拦截器以及api集中管理配置
2.2 main.js中进行引入请求拦截器
2.3 页面中引入请求方法并使用
1.前言
uview2.0是uniapp开发中使用频率相对来讲比较高的一款框架,今天从实战角度介绍一下关于http请求uview是如何进行封装.
该插件支持post 、get 、put和delete ,以及上传下载等请求 ,有如下特点:基于Promise对象实现更简单的request使用方式 ,支持请求和响应拦截
支持全局挂载
支持多个全局配置实例
支持自定义验证器
支持文件上传/下载
支持task 操作
支持自定义参数
支持多拦截器 对参数的处理比uni.request更强
2.使用步骤
2.1 配置请求拦截器以及api集中管理配置
这两个文件夹都返回在项目根目录下的common文件夹下.
api集中管理配置http.api.js内容: const http = uni.$u.http // 根据wx.login获取的code获取小程序openID(get请求路径传参,不传递token) export const getOpenId = (data) => http.get(/user/getOpenId, data) // 注意:如果get请求中没有请求参数可以省略data,具体方法中也不用传递参数; // 根据wx.login获取的code获取小程序openID(get请求路径传参,传递token) export const getOpenIdByToken = (data,config = {}) => http.get(/user/getOpenId, data,config) // post请求,用户登录(post请求请求体传参不传递token) export const login = (params, config = {}) => http.post(/user/login, params, config) // post请求,传递内容(post请求请求路径传参传递token) export const throwBottle = (params, config = {}) => http.post(/drift/send?content=+params.content,params, config)请求拦截器http.interceptor.js内容:
// 此vm参数为页面的实例 ,可以通过它引用vuex中的变量 module.exports = (vm) => { // 初始化请求配置 uni.$u.http.setConfig((config) => { /* config 为默认全局配置*/ config.baseURL = http://127.0.0.1:8080; /* 根域名 */ return config }) // 请求拦截 uni.$u.http.interceptors.request.use((config) => { //根据custom参数中配置的是否需要token ,添加对应的请求头 if(config?.custom?.auth) { // 本处使用的是获取缓存中的token信息,也可以在此通过vm引用vuex中的变量 ,具体值在vm.$store.state中 config.header.token = uni.getStorageSync("token") } return config }, config => { // 可使用async await 做异步操作 return Promise.reject(config) }) uni.$u.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/ if (response.data.code !== 200) { // 服务端返回的状态码不等于200 ,则reject() return Promise.reject(response) } // return Promise.reject 可使promise状态进入catch if (response.config.custom.verification) { // 演示自定义参数的作用 return response.data } return response }, (response) => { /* 对响应错误做点什么 (statusCode !== 200)*/ console.log(response) return Promise.reject(response) }) }
2.2 main.js中进行引入请求拦截器
main.js内容:
import App from ./App // #ifndef VUE3 import Vue from vue Vue.config.productionTip = false App.mpType = app // 引入 store import store from @/store/index.js Vue.prototype.$store = store const app = new Vue({ ...App, store }) // 引入全局uView import uView from ./uni_modules/uview-ui Vue.use(uView) // 引入请求封装 ,将app参数传递到配置中 require(./common/http.interceptor.js)(app) app.$mount() // #endif // #ifdef VUE3 import { createSSRApp } from vue export function createApp() { const app = createSSRApp(App) return { app } } // #endif
2.3 页面中引入请求方法并使用
以下demo中将常用的请求方式进行了分类,并添加了是否传递token的传参方式.
post请求体传参(不传递token)
post请求路径传参(传递token)
get请求路径传参(不传递token)
get请求路径传参(传递token)示例页面截图:
页面内容:
<template> <view> <view>消息页面</view> <!-- 发送请求 --> <view> <button type="primary" @click="method1()">post请求体传参(不含token)</button> </view> <view> <button type="primary" @click="method2()">post路径传参(含token)</button> </view> <view> <button type="primary" @click="method3()">get请求路径传参(不含token)</button> </view> <view> <button type="primary" @click="method4()">get请求路径传参(含token)</button> </view> </view> </template> <script> import { login, send, getOpenId, getOpenIdByToken } from ../../common/http.api.js; export default { data() { }, methods:{ method1(){ this.serverLogin() }, method2(){ this.serverSend("478") }, method3(){ this.serverOpenId("123") }, method4(){ this.serverOpenIdByToken("456") }, serverSend(content) { send({ content: content }, { custom: { auth: true } } ).then(response => { console.log("发送信息:" + JSON.stringify(response)) }).catch((data) => { console.log("发送消息失败:" + JSON.stringify(data)) uni.showToast({ title: "网络不给力,请稍后再试!" }) }) }, serverLogin() { login({ "loginType": 1, "openId": "123" } ).then(response => { console.log("登录信息:"+JSON.stringify(response)) uni.setStorageSync(token,response.data.data.token) }).catch((data) => { console.log("登录失败:" + JSON.stringify(data)) uni.showToast({ title: "网络不给力,请稍后再试!" }) }) }, serverOpenIdByToken(jsCode){ getOpenId({ data:{ "jsCode":jsCode }, custom: { auth: true } } ).then(response => { console.log("openId信息:"+JSON.stringify(response)) }).catch((data) => { console.log("openId信息获取失败:" + JSON.stringify(data)) uni.showToast({ title: "网络不给力,请稍后再试!" }) }) }, serverOpenId(jsCode){ getOpenId({ data:{ "jsCode":jsCode } } ).then(response => { console.log("openId信息:"+JSON.stringify(response)) }).catch((data) => { console.log("openId信息获取失败:" + JSON.stringify(data)) uni.showToast({ title: "网络不给力,请稍后再试!" }) }) } } } </script> <style lang="scss"> .u-page__item__slot-icon{ width: 50rpx; height:50rpx; } </style>补充:使用post请求进行无参的退出操作(注意要传递一个空对象):
api.js: export const logout = (params,config = {}) => http.post(/logout,params, config)页面:
logout({},{ custom: { auth: true } } ).then(response => { // 退出操作逻辑 }).catch((data) => { console.log("用户退出失败:" + JSON.stringify(data)) uni.showToast({ title: data.data.msg, icon : none }) })以上是使用uview2.0封装http请求的处理过程记录,如果感觉有所帮助欢迎评论区留言点赞或是收藏!
官方地址链接:https://www.uviewui.com/js/http.html创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!