javascript - 类型错误 : adapter is not a function error when using axios and webpack in Chrome extension

标签 javascript typescript webpack google-chrome-extension axios

我正在构建一个 chrome 扩展,当从内容脚本收到某些消息时,它需要进行 API 调用。我在发出 HTTP 请求时遇到了困难,我相信我的 webpack 配置是罪魁祸首。
我试过使用 node-fetchaxios也不适合我。
我的 webpack.common.js 文件如下所示:


const path = require("path");

module.exports = {
  target: "node",
  entry: {
    popup: path.join(__dirname, "src/popup/index.tsx"),
    background: path.join(__dirname, "src/background.ts"),
    contentScript: path.join(__dirname, "src/contentScript.ts"),
  },
  output: {
    path: path.join(__dirname, "dist"),
    filename: "[name].js",
  },
  module: {
    rules: [
      {
        exclude: /node_modules/,
        test: /\.tsx?$/,
        use: "ts-loader",
      },
      {
        exclude: /node_modules/,
        test: /\.scss$/,
        use: [
          {
            loader: "style-loader", // Creates style nodes from JS strings
          },
          {
            loader: "css-loader", // Translates CSS into CommonJS
          },
          {
            loader: "sass-loader", // Compiles Sass to CSS
          },
        ],
      },
    ],
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"],
  },
};

当脚本尝试从 chrome 扩展调用 axios 时,我收到此错误:

dispatchRequest.js:52 Uncaught (in promise) TypeError: adapter is not a function
    at dispatchRequest (dispatchRequest.js:52)

最佳答案

我迟到了 10 个月,但这对任何有同样问题的人都有用。从 Axios 迁移到 fetch 可能是一个不错的选择,但如果您在 Axios 之上构建了一个自定义 API 及其所有实用程序(拦截器、取消等),那么工作量很大,因此有一个简单的修复:
Axios 在其 configuration 中接受适配器字段, 所以你可以传递一个像 axios-fetch-adapter 这样的获取适配器可能,您需要添加 regenerator-runtime也是,所以在你的 background.js 文件中:

import "regenerator-runtime/runtime.js";

关于javascript - 类型错误 : adapter is not a function error when using axios and webpack in Chrome extension,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66305856/

相关文章:

javascript - 如何使用 JS 将内容附加到两个不同的 Div?

javascript - 在 React 中使用 Jquery 的正确方法是什么?

javascript - 输入焦点上的 iOS 键盘部分触发

typescript - 使用 TypeScript 在 mongoose.Schema 中的 `required` 字段中使用函数

css - reactjs元素如何添加CSS配置?

javascript - 服务器是否总是按照发送顺序接收 AJAX 请求?

javascript - 如何在知道前两个点和到下一个点的距离的情况下获得下一个点的坐标

javascript - 我怎样才能优化这个 Angular 代码?

reactjs - 使用 React、Typescript 和 Webpack 显示静态图像

javascript - 以下 `src=' ${loadingGif }'` 如何在 Angular 组件内工作