【uni-app】axios 报错:Error: Adapter ‘http‘ is not available in the build

在 uni-app 中使用 axios 会报错:Error: Adapter 'http' is not available in the build

解决方法:为 axios 添加 adapter 适配器。

js 复制代码
import axios from 'axios';
import settle from '../../node_modules/axios/lib/core/settle';
import buildURL from '../../node_modules/axios/lib/helpers/buildURL';

// 设置基础URL
axios.defaults.baseURL = 'http://localhost:3000';

// 解决 uniapp 适配axios请求,避免报adapter is not a function错误
axios.defaults.adapter = function (config) {
  const { method } = config;
  return new Promise((resolve, reject) => {
    uni.request({
      url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
      method: method?.toUpperCase(),
      header: { ...config.headers },
      data: config.data,
      responseType: config.responseType,
      complete: function complete(response) {
        const { data, statusCode, errMsg, header } = response;
        const responseInfo = {
          data,
          status: statusCode,
          errMsg,
          header,
          config: config,
        };
        settle(resolve, reject, responseInfo);
      },
    });
  });
};

// 请求拦截器
axios.interceptors.request.use(
  config => {
    const token = uni.getStorageSync('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    // 处理401错误(未授权)
    if (error.response && error.response.status === 401) {
      uni.removeStorageSync('token');
      uni.removeStorageSync('user');
      uni.showToast({
        title: '登录已过期,请重新登录',
        icon: 'none'
      });
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 认证相关API
export const authAPI = {
  register: (userData) => axios.post('/api/auth/register', userData), // 已使用
  login: (credentials) => axios.post('/api/auth/login', credentials), // 已使用
  getCurrentUser: (object) => axios.post('/api/auth/me', object), // 已使用
  updateProfile: (profileData) => axios.put('/api/auth/profile', profileData)
};
相关推荐
、我是男生。1 小时前
MQTT、HTTP短轮询、HTTP长轮询、WebSocket
websocket·网络协议·http
小徐Chao努力1 小时前
【计网】SSL/TLS核心原理
网络·网络协议·ssl
老李不敲代码5 小时前
榕壹云无人共享系统:基于SpringBoot+MySQL+UniApp的物联网共享解决方案
spring boot·物联网·mysql·微信小程序·uni-app·软件需求
—Qeyser8 小时前
用 Deepseek 写的uniapp血型遗传查询工具
前端·javascript·ai·chatgpt·uni-app·deepseek
codingandsleeping8 小时前
HTTP1.0、1.1、2.0 的区别
前端·网络协议·http
小满blue8 小时前
uniapp实现目录树效果,异步加载数据
前端·uni-app
Monly218 小时前
Uniapp: 大纲
uni-app
张太行_10 小时前
UDP目标IP不存在时的发送行为分析
网络协议·tcp/ip·udp
SlientICE11 小时前
TCP是什么?不需要!使用ESP32网络层直接通信!
网络·单片机·网络协议·tcp/ip
帽儿山的枪手11 小时前
通过网络命名空间实现网络分流的思想及方法
网络协议·docker·dns