uniapp封装request函数的方式是甚么
在uniapp中,可以通过封装一个request函数来发送网络要求。以下是一种常见的封装方式:
export const request = (url, method, data) => {
// 返回一个Promise对象,用于异步处理网络要求结果
return new Promise((resolve, reject) => {
uni.request({
url: url,
method: method,
data: data,
success: (res) => {
// 要求成功时,调用resolve函数并传递结果
resolve(res.data);
},
fail: (error) => {
// 要求失败时,调用reject函数并传递毛病信息
reject(error);
}
});
});
};
import { request } from '@/utils/api.js';
// 在页面的某个方法中发送网络要求
request('http://api.example.com/user', 'GET', {id: 1})
.then((res) => {
// 处理要求成功的结果
console.log(res);
})
.catch((error) => {
// 处理要求失败的毛病
console.log(error);
});
通过这类方式封装request函数,可以更方便地发送网络要求,并对要求结果进行处理。同时,也能够在request函数中添加一些拦截器、统一处理毛病等功能,提高开发效力。
TOP