Network request (uni.request)
uni-app is a framework for developing cross-platform applications using Vue.js, supporting compilation to multiple platforms. uni.request
is the network request API provided by uni-app, used to initiate HTTP requests. Its usage is similar to WeChat Mini Program's wx.request
, but it can be used cross-platform in uni-app.
Basic Usage of uni.request
uni.request
is an asynchronous method used to send HTTP requests. Its basic syntax is as follows:
uni.request({
url: 'https://example.com/api',
method: 'GET',
data: {
key1: 'value1',
key2: 'value2'
},
header: {
'Content-Type': 'application/json'
},
success: (res) => {
console.log(res.data);
},
fail: (err) => {
console.error(err);
},
complete: () => {
console.log('Request completed');
}
});
Parameter Description
url
: The interface address to request (required).method
: The request method, such asGET
,POST
,PUT
,DELETE
, etc. Defaults toGET
.data
: Request parameters, which can be an object or string.header
: Request headers, where you can setContent-Type
, etc.success
: Callback function for a successful request, returning the response data.fail
: Callback function for a failed request, returning error information.complete
: Callback function executed when the request completes (regardless of success or failure).
Sending a GET Request
GET requests are typically used to fetch data. Here’s an example of fetching user information:
uni.request({
url: 'https://api.example.com/users',
method: 'GET',
data: {
userId: 123
},
success: (res) => {
console.log('User info:', res.data);
},
fail: (err) => {
console.error('Request failed:', err);
}
});
Sending a POST Request
POST requests are typically used to submit data. Here’s an example of submitting a form:
uni.request({
url: 'https://api.example.com/submit',
method: 'POST',
data: {
name: 'Zhang San',
age: 25
},
header: {
'Content-Type': 'application/json'
},
success: (res) => {
console.log('Submission successful:', res.data);
},
fail: (err) => {
console.error('Submission failed:', err);
}
});
Setting Request Headers
Request headers can be set via the header
parameter. For example, setting Authorization
for authentication:
uni.request({
url: 'https://api.example.com/protected',
method: 'GET',
header: {
'Authorization': 'Bearer your_token_here'
},
success: (res) => {
console.log('Protected data:', res.data);
}
});
Handling Response Data
The res
parameter in the success
callback contains the following fields:
data
: Data returned by the server.statusCode
: HTTP status code.header
: Response headers.
uni.request({
url: 'https://api.example.com/data',
success: (res) => {
console.log('Status code:', res.statusCode);
console.log('Response headers:', res.header);
console.log('Data:', res.data);
}
});
Error Handling
Use the fail
callback to handle request failures:
uni.request({
url: 'https://api.example.com/error',
fail: (err) => {
console.error('Request error:', err);
// Display an error message here
uni.showToast({
title: 'Network request failed',
icon: 'none'
});
}
});
Using async/await
uni.request
also supports Promise-style calls and can be used with async/await
:
async function fetchData() {
try {
const res = await uni.request({
url: 'https://api.example.com/data',
method: 'GET'
});
console.log('Data:', res[1].data); // Note: Returns an array [err, res]
} catch (err) {
console.error('Request failed:', err);
}
}
fetchData();
Setting Request Timeout
Use the timeout
parameter to set the request timeout (in milliseconds):
uni.request({
url: 'https://api.example.com/slow',
timeout: 5000, // 5-second timeout
success: (res) => {
console.log('Request successful:', res.data);
},
fail: (err) => {
console.error('Request timeout or failed:', err);
}
});
File Upload
uni.uploadFile
is used for file uploads, but you can also implement file uploads with uni.request
(requires manual handling of FormData):
uni.chooseImage({
success: (chooseRes) => {
const tempFilePaths = chooseRes.tempFilePaths;
uni.request({
url: 'https://api.example.com/upload',
method: 'POST',
filePath: tempFilePaths[0],
name: 'file',
formData: {
userId: '123'
},
success: (uploadRes) => {
console.log('Upload successful:', uploadRes.data);
}
});
}
});
Interceptors
uni-app does not natively provide interceptor functionality, but you can implement it by encapsulating uni.request
:
const request = (options) => {
// Add global request headers
const defaultHeader = {
'X-Requested-With': 'XMLHttpRequest'
};
options.header = Object.assign(defaultHeader, options.header || {});
// Add token
const token = uni.getStorageSync('token');
if (token) {
options.header.Authorization = `Bearer ${token}`;
}
return new Promise((resolve, reject) => {
uni.request({
...options,
success: (res) => {
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(res.data);
} else {
reject(res);
}
},
fail: (err) => {
reject(err);
}
});
});
};
// Using the encapsulated request
request({
url: 'https://api.example.com/data',
method: 'GET'
}).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
Cross-Origin Issues
In development environments, you may encounter cross-origin issues. Solutions include:
- Configuring a proxy in
manifest.json
:
{
"h5": {
"devServer": {
"proxy": {
"/api": {
"target": "https://api.example.com",
"changeOrigin": true,
"pathRewrite": {
"^/api": ""
}
}
}
}
}
}
Then request the /api
path in your code.
- Have the backend set CORS headers.
Practical Example
Here’s a complete user login example:
// Login method
async function login(username, password) {
try {
const res = await uni.request({
url: 'https://api.example.com/login',
method: 'POST',
data: {
username,
password
},
header: {
'Content-Type': 'application/json'
}
});
const data = res[1].data;
if (data.token) {
uni.setStorageSync('token', data.token);
uni.showToast({
title: 'Login successful',
icon: 'success'
});
return true;
} else {
throw new Error(data.message || 'Login failed');
}
} catch (err) {
uni.showToast({
title: err.message,
icon: 'none'
});
return false;
}
}
// Calling in a page
login('admin', '123456').then(success => {
if (success) {
uni.navigateTo({
url: '/pages/home/index'
});
}
});
Performance Optimization Tips
- Set Caching Appropriately: For infrequently changing data, use
uni.setStorage
to cache responses. - Combine Requests: Reduce the number of requests by merging multiple APIs into one.
- Cancel Requests: Cancel unresponsive requests to avoid resource waste.
- Compress Data: Work with the backend to use gzip compression for responses.
// Caching example
async function getCachedData() {
const cacheKey = 'cached_data';
const cachedData = uni.getStorageSync(cacheKey);
if (cachedData) {
return cachedData;
}
const res = await uni.request({
url: 'https://api.example.com/data'
});
const data = res[1].data;
uni.setStorageSync(cacheKey, data);
return data;
}
Notes
- In WeChat Mini Programs, the
url
inuni.request
must be configured in therequest
legal domain list. - On the H5 side, cross-origin issues require backend cooperation or a proxy.
- If the
data
parameter is an object, it will automatically be converted to a query string (GET) or request body (POST). - In Alipay Mini Programs, when
content-type
isapplication/json
, you need to manually convertdata
to a JSON string.
Advanced Usage
For larger projects, further encapsulation is possible:
// http.js
const baseURL = 'https://api.example.com';
const http = {
get(url, data) {
return this.request('GET', url, data);
},
post(url, data) {
return this.request('POST', url, data);
},
request(method, url, data) {
return new Promise((resolve, reject) => {
uni.request({
url: baseURL + url,
method,
data,
header: {
'Authorization': `Bearer ${uni.getStorageSync('token')}`
},
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data);
} else {
reject(res.data);
}
},
fail: (err) => {
reject(err);
}
});
});
}
};
export default http;
// Usage example
import http from './http.js';
http.get('/users').then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn