uni-app中ajax请求uni-request封装
    		       		warning:
    		            这篇文章距离上次修改已过444天,其中的内容可能已经有所变动。
    		        
        		                
                在uni-app中,你可以使用uni.request方法来进行HTTP请求,这是一个应用于uni-app的跨平台请求方法。
以下是一个简单的uni-request封装示例:
function uniRequest(options) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: options.url, // 请求的URL
      method: options.method || 'GET', // 请求方法,默认为GET
      data: options.data || {}, // 请求参数
      header: options.header || { 'Content-Type': 'application/json' }, // 设置请求的 header
      success: (res) => {
        // 请求成功处理
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          // 可以根据项目需求修改错误处理
          reject(res.errMsg);
        }
      },
      fail: (err) => {
        // 请求失败处理
        reject(err);
      }
    });
  });
}
 
// 使用封装后的uniRequest方法
uniRequest({
  url: 'https://example.com/api/data',
  method: 'GET'
}).then(response => {
  console.log('请求成功:', response);
}).catch(error => {
  console.error('请求失败:', error);
});在这个封装中,我们创建了一个uniRequest函数,它接收一个对象作为参数,这个对象包含了请求的url、method、data、header等信息。然后我们使用Promise来处理异步请求,在请求成功时调用resolve,失败时调用reject。在实际使用中,你可以根据项目的具体需求对这个封装进行相应的调整。
评论已关闭