You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在React Chrome扩展中使用Axios遇报错:Adapter 'http'不可用

解决Chrome扩展中Axios报错“Adapter 'http' is not available in the build”

这个报错是因为Axios在Chrome扩展的打包环境中无法找到适配的HTTP适配器,以下是几种可行的解决方法:

方法一:指定使用浏览器适配器

直接导入Axios的浏览器预编译版本,或手动配置XMLHttpRequest适配器:

  1. 切换到浏览器版本导入:
import axios from 'axios/dist/axios.min.js';
  1. 手动配置适配器:
import axios from 'axios';
import browserAdapter from 'axios/lib/adapters/xhr';

axios.defaults.adapter = browserAdapter;

方法二:调整打包工具配置

避免打包工具tree-shake掉Axios的适配器代码,以Webpack或Vite为例:

Webpack配置

在webpack.config.js中添加别名:

module.exports = {
  resolve: {
    alias: {
      'axios': 'axios/dist/axios.min.js'
    }
  }
};

Vite配置

在vite.config.ts中添加别名:

import { defineConfig } from 'vite';

export default defineConfig({
  resolve: {
    alias: {
      'axios': 'axios/dist/axios.min.js'
    }
  }
});

方法三:降级Axios版本

Axios 1.x部分版本在浏览器扩展环境中适配存在问题,可降级到稳定的0.26.x版本:

npm uninstall axios
npm install axios@0.26.1

方法四:改用Chrome扩展原生Fetch API

直接使用浏览器原生fetch,无需依赖Axios,更适配Chrome扩展环境:

// background.ts
fetch("https://realtor.p.rapidapi.com/locations/v2/auto-complete", {
  method: 'GET',
  headers: {
    'X-RapidAPI-Key': '你的API密钥',
    'X-RapidAPI-Host': 'realtor.p.rapidapi.com'
  }
})
.then(response => response.json())
.then(data => {
  this.Storage.setLocalStorage(data).then(() => {
    resolve(data.Listeners);
  });
})
.catch(err => {
  reject(new Error(err));
});

内容的提问来源于stack exchange,提问作者DotNetStar A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:25:42