位置: IT常识 - 正文
推荐整理分享uview2.0封装http请求实战以及常见请求传参实录,希望有所帮助,仅作参考,欢迎阅读内容。
文章相关热门搜索词:,内容如对您有帮助,希望把文章链接给更多的朋友!
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状态进入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内容:
import App from './App'// #ifndef VUE3import Vue from 'vue'Vue.config.productionTip = falseApp.mpType = 'app'// 引入 store import store from '@/store/index.js'Vue.prototype.$store = storeconst app = new Vue({ ...App,store})// 引入全局uViewimport uView 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 }}// #endif2.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
上一篇:土豆发芽了能吃吗?慎吃发了芽的土豆(土豆发芽了能吃吗有没有毒)
下一篇:ashserv.exe是什么进程 安全吗 ashserv进程有什么作用(assoc.exe=exefile什么意思)
友情链接: 武汉网站建设