【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)
};
相关推荐
半壶清水5 分钟前
[软考网规考点笔记]-局域网之以太网标准
网络·笔记·网络协议·考试
笨笨狗吞噬者40 分钟前
uni-app 编译小程序原生组件时疑似丢属性,可以给官方提 PR 了
前端·微信小程序·uni-app
初九之潜龙勿用2 小时前
C# 解决“因为算法不同,客户端和服务器无法通信”的问题
服务器·开发语言·网络协议·网络安全·c#
zt1985q4 小时前
本地部署 Home Assistant 高级自动化 AppDaemon 并实现外部访问
运维·服务器·网络·网络协议·自动化
野犬寒鸦7 小时前
计网复习Day01
服务器·后端·网络协议·面试
浅念-7 小时前
Linux 进程与操作系统
linux·运维·服务器·网络·数据结构·笔记·网络协议
大地的一角7 小时前
(计算机网络)传输层协议原理
网络协议·计算机网络·udp
雨声不在7 小时前
IP路由表(ip rule)修改
网络·网络协议·tcp/ip
Alan Lan8 小时前
通过socket获取和解析udp的导航数据
网络·网络协议·udp
雨雨雨雨雨别下啦8 小时前
【从0开始学前端】从0搭建uni-app小程序脚手架
小程序·uni-app