1. 项目初始化
打开 HBuilderX,新建 “UniApp 项目”,选择 “默认模板”,命名为uniapp-demo。
2. 封装网络请求(utils/request.js)
javascript
运行
// 封装uni.request,统一处理请求头、异常、路径前缀
const baseUrl = "http://localhost:8080/api"; // 后端接口前缀
export const request = (options) => {
return new Promise((resolve, reject) => {
uni.request({
url: baseUrl + options.url,
method: options.method || "GET",
data: options.data || {},
header: {
"Content-Type": "application/json"
},
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data);
} else {
uni.showToast({
title: "请求失败",
icon: "none"
});
reject(res);
}
},
fail: (err) => {
uni.showToast({
title: "网络异常",
icon: "none"
});
reject(err);
}
});
});
};
3. 页面调用后端接口(pages/user/user.vue)
vue
<template>
<view class="user-container">
<button @click="getUserList">查询所有用户</button>
<button @click="addUser">新增用户</button>
<view v-for="user in userList" :key="user.id">
<text>用户名:{{user.username}},手机号:{{user.phone}}</text>
</view>
</view>
</template>
<script>
import { request } from "@/utils/request.js";
export default {
data() {
return {
userList: []
};
},
methods: {
// 查询所有用户
async getUserList() {
const res = await request({
url: "/user/list",
method: "GET"
});
this.userList = res;
},
// 新增用户
async addUser() {
const res = await request({
url: "/user/add",
method: "POST",
data: {
username: "test",
password: "123456",
phone: "13800138000"
}
});
if (res) {
uni.showToast({
title: "新增成功"
});
this.getUserList(); // 新增后刷新列表
}
}
}
};
</script>
<style scoped>
.user-container {
padding: 20rpx;
}
button {
margin-bottom: 20rpx;
}
</style>