【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 小时前
Modbus TCP 转 Profinet 主站网关如何应用?
网络·网络协议·tcp/ip
发光小北7 小时前
Modbus TCP 转 Profibus DP 网关如何应用?
网络协议
灰子学技术7 小时前
Envoy HTTP 过滤器处理技术文档
网络·网络协议·http
心中无石马8 小时前
uniapp引入tailwindcss4.x
前端·css·uni-app
fix一个write十个9 小时前
【uniApp开发】微信小程序 web-view 内嵌 H5 跳转支付踩坑实录
微信小程序·uni-app
刘马想放假11 小时前
GRE 隧道深度解析:从协议原理到生产实践
网络协议·安全
@CLoudbays_Martin1111 小时前
UniApp是否能够接入SDK游戏盾呢?
服务器·网络·网络协议·tcp/ip·安全
AIwenIPgeolocation11 小时前
IP地址数据服务:驱动电子商务精细化运营与智能风控
大数据·网络协议·tcp/ip
tang7778911 小时前
代理IP质量检测实战:Python实现IP可用性、延迟、匿名度自动测试脚本
大数据·爬虫·python·网络协议·tcp/ip
科技牛牛11 小时前
街道级IP定位能解决什么问题?哪些团队更适合用
网络·网络协议·tcp/ip·街道级ip定位