在 Chrome 扩展中使用 axios 和 webpack 时出现 TypeError:adapter is not a function 错误

问题描述 投票:0回答:4

我正在构建一个 Chrome 扩展,当从内容脚本收到某些消息时,该扩展需要进行 API 调用。我在发出 HTTP 请求时遇到困难,我相信我的 webpack 配置是罪魁祸首。

我尝试过使用

node-fetch
axios
,但都不适合我。

我的 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)

javascript typescript webpack google-chrome-extension axios
4个回答
21
投票

我好像晚了 10 个月,但这对于遇到同样问题的人来说可能很有用。从 Axios 迁移到 fetch 可能是一个不错的选择,但如果您在 Axios 及其所有实用程序(拦截器、取消等)之上构建了自定义 API,那么工作量会很大,因此有一个简单的修复方法:

Axios 在其 configuration 中接受适配器字段,因此您可以传递像 axios-fetch-adapter 这样的获取适配器,并且可能您还需要添加 regenerator-runtime ,因此在您的 background.js 文件中:

import "regenerator-runtime/runtime.js";

11
投票

我也遇到了类似的问题。 我认为在 chrome 扩展的 Service Worker 上使用 axios 时会发生这种情况。

当访问其他来源并在 chrome 扩展的 Service Worker 上获取响应(即 CROS)时,我可以通过执行以下操作来请求它们

首先,你不能在Service Worker上使用axios。 axios 在获取适配器时尝试使用 xhr 和 http,但不能在 Service Worker 上同时使用这两者。所以,使用fetch,应该是cros模式。

要在cros模式下使用fetch,请将目标URL放入host_permissions中。我在其他网站上看到过权限中 URL 的示例,但如果不使用 host_permissions,则会出现错误。

实际代码应如下所示。 (部分摘录)

清单.json

  "background": {
    "service_worker": "background.js"
  },
  "host_permissions": ["https://sample.com/*"]

背景.js

const res = await fetch(baseUrl + word, {        
method: "GET",        
mode: "cors",      
});      
const txt = await res.text();

我在下面写了更详细的项目历史,希望大家在翻译的时候看一下。

https://takumi-oda.com/blog/2021/09/30/post-2006/


0
投票

我也遇到过同样的问题。尝试这个包 - https://www.npmjs.com/package/ky 到目前为止它对我来说效果很好。它还内置了失败重试功能。


0
投票

除了piedra的答案之外,axios现在在

v1.7.0-beta.0
https://github.com/axios/axios/pull/6371

中有获取适配器
© www.soinside.com 2019 - 2024. All rights reserved.