Master uni.request: Send GET/POST, Handle Data, Loading and Errors in 5 Minutes
This tutorial walks through Uniapp's uni.request API, explaining its purpose, showing the full syntax, and providing step‑by‑step GET and POST examples with loading indicators, error handling, mini‑program domain setup, and common troubleshooting tips for seamless front‑back communication.
Core Goal
Master the complete usage of uni.request , including sending GET/POST requests, handling responses, showing loading indicators, and capturing errors to achieve real front‑back interaction.
Prerequisites
Familiarity with basic components, data binding, list rendering, and dialog APIs.
1. What is uni.request?
It is the official network request API provided by Uniapp, used to:
Fetch data from the backend (e.g., product lists, news, user information).
Submit data to the backend (e.g., login, registration, forms, comments).
A single code base works on H5, mini‑programs, and native apps.
2. Standard Complete Syntax
uni.request({
// URL (required)
url: "https://api.example.com/list",
// Request method GET / POST (default GET)
method: "GET",
// Parameters sent to the backend
data: {
page: 1,
size: 10
},
// Request headers (e.g., token)
header: {
"Content-Type": "application/json"
},
// Success callback
success: (res) => {
console.log("Success data", res.data);
},
// Failure callback
fail: (err) => {
console.log("Request failed", err);
uni.showToast({ title: "Network error", icon: "none" });
},
// Complete callback (executed regardless of outcome)
complete: () => {
uni.hideLoading(); // Close loading indicator
}
});3. Practice 1 – GET Request (Fetching List Data)
Typical use: retrieve product lists, article lists, or other data for display.
<template>
<view>
<view v-for="item in list" :key="item.id" class="item">
<text>{{ item.title }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
list: [] // Receives data
};
},
onLoad() {
// Request data when the page loads
this.getData();
},
methods: {
getData() {
// Show loading indicator
uni.showLoading({ title: "Loading..." });
uni.request({
url: "https://jsonplaceholder.typicode.com/posts", // Test API
method: "GET",
success: (res) => {
// Assign returned data to the page
this.list = res.data;
uni.showToast({ title: "Load successful" });
},
fail: () => {
uni.showToast({ title: "Request failed", icon: "none" });
},
complete: () => {
uni.hideLoading();
}
});
}
}
};
</script>
<style scoped>
.item { padding: 20rpx; border-bottom: 1rpx solid #eee; }
</style>4. Practice 2 – POST Request (Submitting Data)
Typical use: login, registration, form submission, or updating information.
// User login example
login() {
uni.request({
url: "https://api.example.com/login",
method: "POST",
// Parameters sent to the backend
data: {
username: "test",
password: "123456"
},
success: (res) => {
console.log("Login result", res.data);
if (res.data.code === 200) {
uni.showToast({ title: "Login successful" });
// Cache token after successful login
uni.setStorageSync("token", res.data.token);
} else {
uni.showToast({ title: "Invalid username or password", icon: "none" });
}
},
fail: () => {
uni.showToast({ title: "Network error", icon: "none" });
}
});
}5. Essential Tips (Before and After Requests)
Before request : call uni.showLoading to improve user experience.
After request : hide the loading indicator inside the complete callback.
On failure : always give the user a toast notification.
Data assignment : use this.variableName = res.data to bind the response to the view.
6. Mini‑Program Specific Considerations
Mini‑programs must configure a legal domain in the WeChat public platform backend.
During development you can disable domain verification in the WeChat DevTools (Settings → Local Settings → Uncheck “Validate domain”).
Before publishing, the domain must be correctly configured; otherwise requests will fail.
7. Common Troubleshooting
Issue 1: Request fails or cannot connect. Check that the interface URL is correct and that domain verification is disabled during development.
Issue 2: Data does not update on the page. Ensure the response is assigned to a variable defined in data, e.g., this.list = res.data.
Issue 3: Backend does not receive POST data. Verify that the request header Content-Type is set to application/json.
Issue 4: Loading spinner never disappears. Call uni.hideLoading() inside the complete callback.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
liandk
Seasoned Java and mobile developer with years of experience, specializing in mini‑programs, public accounts, and full‑stack front‑end development. In the AI era, I continuously learn to broaden my knowledge and evolve. I revived a public account I started a decade ago during a dessert‑startup venture, using code as a vessel and knowledge as a companion. I share personal projects, technical articles, programming tips, and growth insights—let’s improve together and set sail.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
