在uniapp中,可以通过封装一个request函数来发送网络请求。以下是一种常见的封装方式:
- 在项目的utils文件夹中创建一个api.js文件。
- 在api.js文件中定义一个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); } }); }); };
- 在需要发送网络请求的页面中引入api.js文件,并调用request函数。
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函数中添加一些拦截器、统一处理错误等功能,提高开发效率。