uni-app encapsulates api requests

1. Encapsulate API request steps

To encapsulate API requests in uni-app, you can follow the following steps:

  1. Create a utils folder and create an api.js file in it to store code related to API requests.

  2. In the api.js file, introduce the uni.request method to send requests. The sample code is as follows:

export function request(url, method, data) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      method: method,
      data: data,
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

Promise objects are used here to handle asynchronous requests to facilitate subsequent use and processing.

  1. In the api.js file, define specific API request functions. The sample code is as follows:
import { request } from './utils/api';

export function login(username, password) {
  const url = 'https://api.example.com/login';
  const method = 'POST';
  const data = {
    username: username,
    password: password
  };
  return request(url, method, data);
}

export function getUserInfo(userId) {
  const url = `https://api.example.com/users/${userId}`;
  const method = 'GET';
  return request(url, method);
}

The above sample code includes two API request functions for logging in and obtaining user information. Based on specific needs, you can modify or add other API request functions.

  1. Just introduce and call the defined API request function in the page or component that needs to use the API. The sample code is as follows:
import { login, getUserInfo } from './utils/api';

login('example', 'password').then((res) => {
  console.log('登录成功', res);
}).catch((err) => {
  console.error('登录失败', err);
});

getUserInfo(123).then((res) => {
  console.log('获取用户信息成功', res);
}).catch((err) => {
  console.error('获取用户信息失败', err);
});

The above sample code shows how to use the encapsulated API request function to log in and obtain user information. According to specific requirements, you can call related API request functions in corresponding pages or components.

Through the above steps, you can encapsulate API requests in uni-app to make the code structure clearer and maintainable. Remember to perform appropriate error handling and data processing according to the actual situation.

2. uni-app encapsulation api request improvement

// @/utils/request.js
// #ifdef MP-WEIXIN
const baseURL = "https://www.bradenhan.tech"
// #endif 
// #ifdef H5
const baseURL = ""
// #endif

const timeout = 5000

// 封装api请求
const request = function(option){ 
    // 获取用户传入的url
    var url = baseURL + option.url; 
     
    // 添加提请求头
    var  header = option.header||{}
    if(!!option.needToken){
        // 添加token 
        header.Authorization =  'Bearer ' +  uni.getStorageSync('token');  
    }
    header.source=1;
    header.channel="h5";
    
    // 加载提示
    var loading = option.loading;
    // 如果有loading就显示loading
    if(loading){
        uni.showLoading(loading)
    }
  
  // 返回一个promise
    return new Promise((resolve,reject)=>{  
        // 发起一个request请求
        uni.request({
            url, //请求url
            method:option.method||"GET", //请求方法
            header, //请求头
            timeout,
            data:option.data||option.params, //请求数据
            success(res){
                // 成功返回结果
                if(res.statusCode===200){
                    resolve(res.data)
                    // 如果是101 没有权限
                    if(res.data.code==101){
                        uni.showToast({
                            title: res.data.msg,
                            icon:'none'
                        })
                        uni.redirectTo({
                            url: '/pages/login/index',
                        })
                    }
                    if(res.data.code!=200&&res.data.code!=0){
                        uni.showToast({
                            icon:'none',
                            title:res.data.msg||'请求错误'
                        })
                    }
                } 
            },
            fail(err){
                // 失败返回失败结果
                uni.showToast({
                    title: '请求失败',
                    icon:'error'
                })
                console.error(err);
                reject(err)
            },
            complete(){
                // 完成 关闭loading
                if(loading){
                    uni.hideLoading()
                }
            }
        })
    })
}

// 定义get简洁方法
request.get=function(url,config){
    return  request({
        url,
        method:"GET",
        ...config
    })
}

// 定义post简洁方法
request.post=function(url,data,config){
    return  request({
        url,
        method:"POST",  
        ...config,
        data
    })
}
// 导出请求
export default request;

Unified control api.js

request.post(url,data,needToken)

parameter:

• url request url

• data request parameter data

• whether needToken requires parameters

// @/api/index.js

import request from '@/utils/request.js' 

// 用户注册
export function customUseRegister(data){
    return request.post("/xxxx1",data)
}

// 微信用户登录
export function customUserLogin(data){
    return request.post("/xxxx2",data)
} 

// 更新用户信息 -- 需要使用Token
export function customUserUpdate(data){
    return request.post("/xxxx3",data,{needToken: true})
}

used in the component

import { customUserLogin, customUseRegister,customUserUpdate } from '@/api/index.js'

customUserUpdate(data).then((res) => {
  console.log('成功', res);  
}).catch((err) => { 
  console.error('登录失败', err);
});

Guess you like

Origin blog.csdn.net/weixin_43025151/article/details/132739550