UniApp API Request: Fetch Backend Data
To fetch data from the backend using UniApp, you can utilize UniApp’s built-in request API: uni.request.
- Use the uni.request method to send a request in the page or component where data is needed.
// 发送GET请求
uni.request({
url: 'http://example.com/api/data', // 请求的接口地址
method: 'GET',
success: res => {
console.log(res.data); // 请求成功后的处理逻辑
},
fail: (err) => {
console.log(err); // 请求失败后的处理逻辑
}
});
// 发送POST请求
uni.request({
url: 'http://example.com/api/data', // 请求的接口地址
method: 'POST',
header: { // 设置请求头,例如传递token等
'Authorization': 'Bearer token'
},
data: { // 请求的参数
key1: 'value1',
key2: 'value2'
},
success: res => {
console.log(res.data); // 请求成功后的处理逻辑
},
fail: (err) => {
console.log(err); // 请求失败后的处理逻辑
}
});
- After a successful request, the data returned by the backend can be accessed through res.data. It can be processed accordingly based on the format of the backend interface response.
- If the data returned from the backend is in JSON format, you can directly access the data through res.data.
- If the backend returns a string, you can use JSON.parse(res.data) to convert the string to a JSON object.
Note: When using uni.request to send a request, you need to set the request method (GET, POST, etc.), request URL, request headers, and request data according to the requirements of the backend interface.
Additionally, you can also use other third-party libraries or plugins to send requests, such as axios, flyio, etc. You can refer to their documentation for specific usage methods.