uniapp 简单封装接口请求

环境配置:utils/env.js

let BASE_URL
// 开发环境
if (process.env.NODE_ENV === 'development') {
  BASE_URL = ''
}
// 生产环境
else {
  BASE_URL = ''
}
export default {
  BASE_URL
}

接口封装:utils/request.js

import env from './env.js'
const request = (options) => {
  // 弹出加载弹窗
  uni.showLoading({
    title: '加载中...'
  });
  return new Promise((resolve, reject) => {
    // 设置请求头
    const header = {
      ...options.header
    }
    // 查询是否存在token,并添加请求头
    if (uni.getStorageSync('token')) header['Authorization'] = `Bearer ${uni.getStorageSync('token')}`
    uni.request({
      url: env.BASE_URL + options.url,
      method: options.method,
      data: options.data,
      header,
      success: (res) => {
        console.log("请求信息: ", env.BASE_URL + options.url, options.data);
        console.log("接口返回: ", res.data);
        switch (res.data.code) {
          case 401:
            uni.clearStorageSync()
            uni.showToast({
              title: '登录状态失效,请重新登录',
              icon: 'none',
            });
            uni.navigateTo({
              url: '/pages/login',
            })
            reject(res.data)
            break;
          case 200:
            resolve(res.data);
            break;
          default:
            uni.showToast({
              title: '未知错误,请联系管理员',
              icon: 'none'
            });
            reject(res.data)
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '请求超时,请稍后重试!',
          icon: 'none'
        });
        reject(err)
      },
    })
    uni.hideLoading();
  })
}
export default request

设置接口:api/login.js

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

/**
 * 登录
 */
export const login = (data) => {
  return request({
    url: '/login',
    method: 'POST',
    data
  })
}

/**
 * 用户信息
 */
export const getInfo = (data) => {
  return request({
    url: '/getInfo',
    method: 'GET',
    data
  })
}

接口使用:

import { login, getInfo } from '@/api/login.js';
 login(params).then((res) => {
 })
posted @ 2025-10-09 12:01  小周同学~  阅读(24)  评论(0)    收藏  举报