news 2026/2/28 12:13:06

uni-app x封装request,统一API接口请求

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
uni-app x封装request,统一API接口请求

config.baseURL = 'https://api.example.com' // api地址

config.timeout = 8000 // 单位毫秒,对应8秒

config.loadingText = '加载中...'

config.loading = true // 开启 loading 动画

return config

})

/* 2. 请求拦截 */

http.interceptors.request.use((config) => {

const token = uni.getStorageSync('token')

if (token) config.header.Authorization = `Bearer ${token}`

return config

})

/* 3. 响应拦截 */

http.interceptors.response.use(

(response) => response.data,

(err) => {

// 🔥 强制断言,让 UTS 闭嘴

(uni as any).$u.toast(err.message || '网络错误')

return Promise.reject(err)

}

)

export default http

复制代码

修改 main.uts,引入 request,并挂载为全局属性$http

复制代码

import App from './App.uvue'

import { createSSRApp } from 'vue'

import uviewPlus from 'uview-plus'

/* 1. 引入 request(里面已经初始化好 http) */

import http from '@/utils/request'

export function createApp() {

const app = createSSRApp(App)

/* 2. 挂到全局属性 */

app.config.globalProperties.$http = http

app.use(uviewPlus)

return {

app

}

}

复制代码

三、使用request

由于在main.uts挂载了全局属性,因此在pages里面的uvue文件,就可以直接调用了。比如:

get请求

const res = await this.$http.get('/test', {})

post请求

const res = await this.$http.post('/login', {

username: 'admin',

password: 123456

})

post请求,增加成功和失败处理

复制代码

async login() {

try {

/* === 成功分支 === */

const res = await this.$http.post('/login', {

username: 'admin',

password: '123456'

})

// 这里只写“成功后的业务”

uni.setStorageSync('token', res.token)

this.$u.toast('登录成功')

uni.switchTab({ url: '/pages/index/index' })

} catch (err: any) {

/* === 失败分支 === */

// 拦截器已弹通用提示,这里可做“额外”处理

console.error('登录失败', err)

if (err.statusCode === 401) {

this.$u.toast('账号或密码错误')

}

}

}

复制代码

post请求,局部请求不想显示 loading

await this.$http.post('/log', data, { loading: false })

uview-plus 的 http 模块已经内置了 “请求开始自动显示 loading,响应结束自动隐藏” 的机制,

你只需要 把 loading 开关打开 即可,成功/失败/超时都会 统一自动关闭,无需手动处理。

效果:

调用 this.$http.get/post 瞬间 → 出现 uview-plus 的 loading 遮罩

请求 成功/失败/超时 → 遮罩 自动消失(由 uview 内部 finally 关闭)

无需自己 uni.showLoading() / uni.hideLoading()

post请求,增加header

复制代码

await this.$http.post('/upload', body, {

header: {

'Content-Type': 'application/x-wwwz-form-urlencoded',

'X-Custom': 'abc123'

}

})

复制代码

put请求

const res = await this.$http.put('/test', {id:1})

delete请求

const res = await this.$http.delete('/test', {id:1})

四、登录页面

login.uvue

复制代码

<template>

<view class="">

<!-- 导航栏 -->

<u-navbar title="用户登录" />

<!-- 内容区 -->

<view class="content">

<!-- 头像 -->

<u-avatar :src="logo" size="80"></u-avatar>

<!-- 表单 -->

<u--form :model="form" labelPosition="left">

<u--input v-model="form.username" placeholder="请输入用户名" prefixIcon="account" />

<u--input v-model="form.password" placeholder="请输入密码" type="password" prefixIcon="lock" />

</u--form>

<!-- 按钮 -->

<u-button text="登录" type="primary" @click="login" />

<!-- 链接 -->

<view class="links">

<u-cell title="忘记密码?" isLink @click="gotoForget" />

<u-cell title="注册账号" isLink @click="gotoRegister" />

</view>

</view>

</view>

</template>

<script>

export default {

data() {

return {

title: 'Hello',

logo: '/static/logo.png',

form: {

username: '',

password: '',

}

}

},

onLoad() {

},

methods: {

async login() {

if (!this.form.username) {

uni.showToast({ title: '请输入用户名', icon: 'none' })

return

}

// 请求登录接口

try {

/* === 成功分支 === */

const res = await this.$http.post('/login', {

username: this.form.username,

password: this.form.password

})

// 这里只写“成功后的业务”

uni.setStorageSync('token', res.token)

this.$u.toast('登录成功')

uni.switchTab({ url: '/pages/index/index' })

} catch (err : any) {

/* === 失败分支 === */

// 拦截器已弹通用提示,这里可做“额外”处理

console.error('登录失败', err)

if (err.statusCode === 401) {

this.$u.toast('账号或密码错误')

}

this.$u.toast('网络请求异常')

}

},

gotoForget() {

uni.navigateTo({ url: '/pages/forget/index' })

},

gotoRegister() {

uni.navigateTo({ url: '/pages/register/index' })

}

}

}

</script>

<style scoped>

.content {

padding: 40rpx;

display: flex;

flex-direction: column;

align-items: center;

}

.links {

margin-top: 30rpx;

width: 100%;

}

</style>

复制代码

效果如下:

image

针对大型项目,可以在utils里面新建一个api.ts,用来编写一些公用业务函数,例如:

复制代码

import http from './request.js'

/* 登录 */

export const login = (username, pwd) =>

http.post('/login', { username, pwd })

/* 轮播图 */

export const getBanner = () =>

http.get('/banner')

/* 商品列表 */

export const getGoods = (params) =>

http.get('/goods', { params })

复制代码

然后在pages里面的页面,就可以调用了,无需重复写函数。

复制代码

<script>

import { getBanner } from '@/utils/api.ts'

export default {

data() {

return {

title: 'Hello',

bannerList: [],

}

},

onLoad() {

this.getbannerList()

},

methods: {

async getbannerList() {

/* 直接调用 */

this.bannerList = await getBanner()

},

}

}

</script>

复制代码

注意:直接调用,要用异步,函数名前面加async

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/2/4 19:32:22

道指创历史新高,甲骨文重挫逾10%拖累科技股

美股市场于12月11日&#xff08;周四&#xff09;收盘时&#xff0c;三大主要股指表现分化。道琼斯工业平均指数收涨1.34%&#xff0c;创下历史新高。然而&#xff0c;标普500指数仅微涨0.2%&#xff0c;纳斯达克综合指数收跌0.25%。个股方面&#xff0c;软件巨头甲骨文股价暴跌…

作者头像 李华
网站建设 2026/2/27 22:42:32

Jaro-Winkler距离算法详解:从拼写纠错到相似度计算

Jaro-Winkler距离是一种衡量两个字符串相似程度的算法&#xff0c;特别适合处理短字符串如姓名、地址、产品型号等的相似性比较。该算法的核心思想是通过字符匹配、顺序分析和前缀加权三个维度综合评估字符串的相似性&#xff0c;返回0到1之间的值&#xff0c;值越接近1表示字符…

作者头像 李华
网站建设 2026/2/28 9:50:00

数据结构:邻接矩阵

邻接矩阵 资料&#xff1a;https://pan.quark.cn/s/43d906ddfa1b、https://pan.quark.cn/s/90ad8fba8347、https://pan.quark.cn/s/d9d72152d3cf 一、邻接矩阵的定义 邻接矩阵是图的一种基础存储方式&#xff0c;通过一个二维数组来表示图中顶点之间的邻接关系。对于包含 n 个顶…

作者头像 李华
网站建设 2026/2/26 5:53:06

插件分享:将AI生成的数学公式无损导出为Word文档

对于经常使用DeepSeek、豆包等AI工具处理技术内容的小伙伴&#xff0c;一个常见的困扰是&#xff1a;生成的回答中包含的数学公式&#xff0c;复制到Word后往往变成难以编辑的代码或模糊图片&#xff0c;手动调整耗时费力。 本文将介绍解决此问题的技术方案和插件&#xff0c;…

作者头像 李华
网站建设 2026/3/1 4:00:42

Ubuntu 22.04 开发环境 CA 证书签发完整笔记(完整版)

Ubuntu 22.04 开发环境 CA 证书签发完整笔记 开发环境 前端: Vue3+TS+Vite+ESM 后端:NestJS 数据库:MySQL+Redis 虚拟机OS:Ubuntu 22.04 LTS 工作拓扑 开发环境参数(VS Code) 版本: 1.106.3 (Universal) Electron: 37.7.0 ElectronBuildId: 12781156 Chromium: 138.0.72…

作者头像 李华