[英]Error in v-on handler (Promise/async): "TypeError: axios__WEBPACK_IMPORTED_MODULE_14___default.a.todo is not a function"
[英]TypeError: adapter is not a function error when using axios and webpack in Chrome extension
我正在構建一個 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)
我遇到了類似的問題。 我認為在 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();
我在下面寫了一個更詳細的項目歷史,希望你在翻譯時能看一下。
我遲到了 10 個月,但這對任何有同樣問題的人都有用。 從 Axios 遷移到 fetch 可能是一個不錯的選擇,但如果您在 Axios 及其所有實用程序的基礎上構建了自定義 API ,那么工作量很大
Axios 在其配置中接受適配器字段,因此您可以傳遞像axios-fetch-adapter 之類的獲取適配器,並且可能還需要添加regenerator-runtime ,因此在您的 background.js 文件中:
import "regenerator-runtime/runtime.js";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.