0


uview2.0封装http请求实战以及常见请求传参实录

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状态进入catchif(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内容:
importApp from './App'// #ifndef VUE3importVue from 'vue'Vue.config.productionTip =falseApp.mpType ='app'// 引入 store importstore from '@/store/index.js'
Vue.prototype.$store = store

const app =newVue({...App,
    store
})// 引入全局uViewimportuView from './uni_modules/uview-ui'
Vue.use(uView)// 引入请求封装,将app参数传递到配置中require('./common/http.interceptor.js')(app)

app.$mount()// #endif// #ifdef VUE3import{ 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
标签: http 前端 uview2.0

本文转载自: https://blog.csdn.net/weixin_43401380/article/details/129473169
版权归原作者 卖柴火的小伙子 所有, 如有侵权,请联系我们删除。

“uview2.0封装http请求实战以及常见请求传参实录”的评论:

还没有评论