【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)
};
相关推荐
阿捏利12 小时前
详解网络协议(十六)UDP协议
网络·网络协议·udp
taxunjishu12 小时前
AGV 与伺服协同控制Profinet 转 Modbus TCP塔讯智能网关仓储场景应用实践
网络·网络协议
情绪雪13 小时前
IP 协议基本原理
网络·网络协议·tcp/ip
Lucas_coding13 小时前
【语音相关ASR】OpenAI 兼容 Qwen_ASR 接口调用实战:SDK 与 HTTP 方式详解
网络·网络协议·http
不会写DN14 小时前
如何设计应用层 ACK 来补充 TCP 的不足?
开发语言·网络·数据库·网络协议·tcp/ip·golang
snow@li14 小时前
协议:应用层开发都会涉及哪些协议 / 详细整理 / http、ws、https、wss
网络协议·http·https
椰猫子15 小时前
Javaweb(Http、Maven)
网络·网络协议·http
小心我捶你啊15 小时前
SOCKS5与HTTP代理的差异与应用场景抉择
网络·网络协议·http
z10_1415 小时前
动态住宅 IP 能做什么?[动态住宅 IP流量包] 免费测试!
服务器·网络协议·tcp/ip
软希网分享源码16 小时前
中英双语言量化交易投资源码/跟单搬砖区块链交易所源码/前端uniapp纯源码+后端
前端·uni-app·区块链·中英双语言量化交易投资源码