【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)
};
相关推荐
熊文豪3 小时前
KingbaseES 数据加密全解:从 SSL 到全密态
网络·网络协议·ssl
网络小江4 小时前
上网第三十八课:TCP 三次握手与四次挥手——连接到底是怎么“谈“成的
网络协议
AIgorithmGEEK5 小时前
[Linux]HTTP 应用层协议全解(下篇)
linux·网络·网络协议·http·cookie·无连接·无状态
DP DPharness5 小时前
手机连不上 DSH 时的排错顺序:从 401 到 WebSocket 放行
websocket·网络协议·智能手机
91刘仁德5 小时前
传输层协议深度拆解:端口寻址、UDP 报文与 TCP 可靠性机制全解析
linux·网络·c++·网络协议·tcp/ip·udp·c
傲世仙尊5 小时前
TCP报头全解-序号确认应答与可靠性是一个准数
驱动开发·网络协议·tcp/ip
AIgorithmGEEK6 小时前
[Linux]HTTP 应用层协议全解(中篇)
linux·网络·网络协议·http
ai_xiaogui6 小时前
PanelAI 1.1.1重磅更新:秒级安装脚本优化 + 无公网IP算力节点组网,私有化AI管理平台全面升级
人工智能·网络协议·tcp/ip·api聚合管理·开发者ai一键部署·ai底层架构解析·ai应用快速变现
91刘仁德6 小时前
HTTPS 加密原理与 CA 数字证书:从对称加密到完整通信流程
网络·笔记·网络协议·http·https