Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adapter is not a function (EDIT: after 1st request) #2968

Closed
tincho opened this issue May 13, 2020 · 24 comments
Closed

adapter is not a function (EDIT: after 1st request) #2968

tincho opened this issue May 13, 2020 · 24 comments

Comments

@tincho
Copy link

tincho commented May 13, 2020

Edit:

I originally thought this was only happening in the DELETE request.
It turns out that any request after the first request fails . So if I send the POST and then the POST again, the 2nd time it fails.

TypeError: adapter is not a function
    at dispatchRequest (dispatchRequest.js:52)
    at async http:/localhost:3004/launchpad/static/js/205.chunk.js:537

--

Hi there

In the same page we have several calls to axios.get, axios.post and those work fine.

But using axios.delete I'm getting a weird error

adapter is not a function

I inspected into axios' code and found that effectively, defaults.adapter is undefined

image (20)

Weird thing is that in other verbs (get, post), adapter is a function (I think is xhrAdapter or something like that)

@tincho tincho changed the title adapter is not a function (axios.delete only) adapter is not a function (EDIT: after 1st request) May 15, 2020
@tincho
Copy link
Author

tincho commented May 15, 2020

I kind of worked around this with this hack:

import axiosOriginal from 'axios'
import adapter from 'axios/lib/adapters/xhr'

const axios = axiosOriginal.create({ adapter })

@chinesedfan
Copy link
Collaborator

It turns out that any request after the first request fails

Maybe your interceptors did something special to the default config. Please check for that.

@tincho
Copy link
Author

tincho commented May 29, 2020

Hello, thanks for the reply!
Indeed, we have a few logger interceptors, that I disabled in order to be able to debug the issue until reaching the "adapter is not a function" point

The interceptors are these:

import * as AxiosLogger from 'axios-logger'
axios.interceptors.request.use(
  AxiosLogger.requestLogger,
  AxiosLogger.errorLogger
)
axios.interceptors.response.use(
  AxiosLogger.responseLogger,
  AxiosLogger.errorLogger
)

but again, those were commented out and the error persisted

@chinesedfan
Copy link
Collaborator

Can you provide a sample and reproducible repo? With limited information, I am sorry that can't find the reason.

@github-actions
Copy link
Contributor

Hello! 👋

This issue is being automatically marked as stale because it has not been updated in a while. Please confirm that the issue is still present and reproducible. If no updates or new comments are received the issue will be closed in a few days.

Thanks.

@softmarshmallow
Copy link

softmarshmallow commented Oct 29, 2020

#3366

Still having the issue. Please re-open

image

image

And this #456 (comment) didn't work for me.

webpack config

const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
const Dotenv = require('dotenv-webpack');
const TerserPlugin = require('terser-webpack-plugin');


module.exports = (env, argv) => ({
    mode: argv.mode === 'production' ? 'production' : 'development',

    // https://github.com/webpack-contrib/css-loader/issues/447#issuecomment-285598881
    node: {
        fs: 'empty',
    },
    // This is necessary because Figma's 'eval' works differently than normal eval
    devtool: argv.mode === 'production' ? false : 'inline-source-map',

    entry: {
        ui: './src/ui.tsx', // The entry point for your UI code
        code: './src/code.ts', // The entry point for your plugin code
    },

    module: {
        rules: [
            // Converts TypeScript code to JavaScript
            { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ },

            // Enables including CSS by doing "import './file.css'" in your TypeScript code
            { test: /\.css$/, loader: [{ loader: 'style-loader' }, { loader: 'css-loader' }] },

            // Allows you to use "<%= require('./file.svg') %>" in your HTML code to get a data URI
            { test: /\.(png|jpg|gif|webp|svg|zip)$/, loader: [{ loader: 'url-loader' }] },

            { test: /\.pug$/, use: ["pug-loader"], }
        ],
    },

    // Webpack tries these extensions for you if you omit the extension like "import './file'"
    resolve: { extensions: ['.tsx', '.ts', '.jsx', '.js'] },

    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'), // Compile into a folder called "dist"
    },

    // minimize
    optimization: {
        minimize: false,
        minimizer: [new TerserPlugin({
            terserOptions: {
                sourceMap: true,
                compress: {
                    keep_classnames: true, // keep class name cause, flutter-builder uses class name reflection.
                    keep_fnames: true,
                    drop_console: true,
                    conditionals: true,
                    unused: true,
                    comparisons: true,
                    dead_code: true,
                    if_return: true,
                    join_vars: true,
                    warnings: false
                },
                output: {
                    comments: false
                }
            }
        })],
    },

    // Tells Webpack to generate "ui.html" and to inline "ui.ts" into it
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/ui.html',
            filename: 'ui.html',
            inlineSource: '.(js)$',
            chunks: ['ui'],
        }),
        new HtmlWebpackInlineSourcePlugin(),
        new Dotenv(),
    ],
})

tsconfig

{
    "compilerOptions": {
      "target": "ES2016",
      "module": "commonjs",
      "lib": [
        "es2017",
        "es7",
        "es6",
        "dom"
      ],
      "jsx": "react",
      "esModuleInterop": true,
      "outDir": "dist",
      "declaration": true,
      "allowSyntheticDefaultImports": true,
      "sourceMap": true,
      "experimentalDecorators": true,
      "noUnusedLocals": false,
      "typeRoots": [
          "./node_modules/@types",
          "../node_modules/@types",
          "../node_modules/@figma",
      ]
    },
    "exclude": [
      "node_modules",
      "dist",
      "example",
      "tests"
    ]
  }

@softmarshmallow
Copy link

import axiosOriginal from 'axios'
import adapter from 'axios/lib/adapters/xhr'

const axios = axiosOriginal.create({ adapter })

XMLHttpRequest is not defined

softmarshmallow added a commit to gridaco/base that referenced this issue Oct 29, 2020
softmarshmallow added a commit to softmarshmallow/uguu-api that referenced this issue Oct 29, 2020
@yennor
Copy link

yennor commented Dec 13, 2020

I've had the same problem.
But my problem was, that I tried to use Axios inside of a service worker. Unfortunately that doesn't work since axios can't work inside of a worker, because of: #1219
So the above solution didn't work (obviously)

@stefanoriva-xs
Copy link

Having same problem but only with my Webpack release.
I've tried different webpack config solutions and i get 2 different errors now:

If i set minimize to false, i get
TypeError: adapter is not a function

If i toogle the minimize to true, i get
TypeError: (config.adapter || defaults.adapter) is not a function

Runs without issues on development, as soon as i bundle it just won't work..

@suhostv
Copy link

suhostv commented Mar 5, 2021

@softmarshmallow, @tincho were you guys able to resolve this issue?
tried a lot of things, but nothing seem to help

@softmarshmallow
Copy link

Wasn't able to. In my case fetch just wasn't allowed in my js environment. (I'm developing a figma plugin)

flaviuse pushed a commit to tcaselli/zoop-modulefed-poc that referenced this issue Mar 12, 2021
@shunjizhan
Copy link

Had similar issue, in my case I was using some polyfill plugin with webpack, which made the production code somehow browser like, so

Object.prototype.toString.call(process) === '[object object]'

Then I ran the code in Node, and axios can't pick any adaptor by this code:

function getDefaultAdapter() {
  var adapter;
  if (typeof XMLHttpRequest !== 'undefined') {
    // For browsers use XHR adapter
    adapter = require('./adapters/xhr');
  } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
    // For node use HTTP adapter
    adapter = require('./adapters/http');
  }
  return adapter;
}

not sure why we need to check Object.prototype.toString.call(process) === '[object process], isn't typeof process !== 'undefined' enough to determine it is a Node environment?

To solve this, turns out I don't actually need the polyfill plugin to build the production code... so I just removed that plugin from webpack, and it worked...

@tkodev
Copy link

tkodev commented Aug 25, 2021

Had similar issue, in my case I was using some polyfill plugin with webpack, which made the production code somehow browser like, so

Object.prototype.toString.call(process) === '[object object]'

Then I ran the code in Node, and axios can't pick any adaptor by this code:

function getDefaultAdapter() {
  var adapter;
  if (typeof XMLHttpRequest !== 'undefined') {
    // For browsers use XHR adapter
    adapter = require('./adapters/xhr');
  } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
    // For node use HTTP adapter
    adapter = require('./adapters/http');
  }
  return adapter;
}

not sure why we need to check Object.prototype.toString.call(process) === '[object process], isn't typeof process !== 'undefined' enough to determine it is a Node environment?

To solve this, turns out I don't actually need the polyfill plugin to build the production code... so I just removed that plugin from webpack, and it worked...

what polyfill plugin were you using?

@MakarovAV
Copy link

MakarovAV commented Sep 20, 2021

I've encountered the same issue recently with a basic webpack+babel+typescript configuration.
For whatever reason, webpack refused to add httpAdapter to the bundle. Even if I required it explicitly, it was replaced by the adapter. I still have not figured out exactly why.

What worked for me: target: 'node' in the webpack config (https://webpack.js.org/concepts/targets/#usage).
If you need the code to work in both browser and node you might need two separate webpack configs.

akindyakov added a commit to mazed-dev/truthsayer that referenced this issue Nov 5, 2021
Replace [`axios`](ttps://github.com/axios/axios) with raw [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) API to talk to smuggler from web (web app, browser extension, etc).

Basically `axios` doesn't work in chrome extension, `axios` GitHub issue axios/axios#2968

- [x] Replace `axios` with `fetch`
- [x] Replaced `axios`'s `CancelToken` with `fetch`'s `AbortControler` all over the truthsayer code
- [x] Separated `archaeologist` build in development and production modes - to use different endpoints of smuggler
- [x] Added simple `ping` from archaeologist background code to test that smuggler API actually works for it
- [x] Added special environment variables for archaeologist to distinguish different bowsers in TS/JS code (not used yet)
- [x] Fixed a problem with cross origin permissions in `archaeologist` by adding `host_permissions` to `manifest.json`
@qiankunxienb
Copy link

I have encountered the same issue when I use axios in chrome extension background.js.

@evanb2
Copy link

evanb2 commented Mar 1, 2022

Also landed here after getting this error trying to use axios in a Chrome extension background file. Sad face.

dominicwbaker added a commit to dominicwbaker/base that referenced this issue Mar 7, 2022
@mehimanshupatil
Copy link

@qiankunxienb @evanb2 what workaround did you applied to resolve

@aadarshp31
Copy link

aadarshp31 commented Oct 14, 2022

I found the solution here: spatie/laravel-server-side-rendering#53 (comment)
Thanks to @SerhiyP

import adapter from 'axios/lib/adapters/http'

axios(URL, {
adapter: adapter
})

Issues
The network logs are not visible in the Chrome Dev Tools if we go via this route.

MY USE CASE
I am working on a vscode web extension which I want to work in desktop (nodejs) environment. Axios was throwing the exact same error for me. This fix helped me resolve this issue.

@tktcorporation
Copy link

tktcorporation commented Oct 17, 2022

I have encountered the same issue when I use axios in a chrome extension background.js.
And I resolved this problem.

My extension is made by forking https://github.com/antfu/vitesse-webext/tree/369fc0386970c77e35d401a2deb4d2ef71768aea .

pnpm add -D @vespaiach/axios-fetch-adapter@0.3.1 axios@0.26.1
import axios from 'axios'
import fetchAdapter from '@vespaiach/axios-fetch-adapter';

const service = axios.create({ adapter: fetchAdapter })

ref: https://zenn.dev/nicopin/articles/5dc87c27bd08de

@MingyuJeon
Copy link

import axios from 'axios'
import fetchAdapter from '@vespaiach/axios-fetch-adapter';

const service = axios.create({ adapter: fetchAdapter })

This works perfect!

@aadarshp31
Copy link

Does anyone have a solution for the same with XMLHttpResquest adapter? I needed it for node environment.

@PedroFolego
Copy link

import axios from 'axios'
import fetchAdapter from '@vespaiach/axios-fetch-adapter';

api.defaults.adapter = fetchAdapter;
const user = await api.get('/users');

This worked for me.
I removed it from the axios.create and put it with the request.

@marcusjwhelan
Copy link

@PedroFolego @tktcorporation @MakarovAV Has anyone been able to solve this when they aren't using axios directly but axios is being used by another library? Sendgrid is getting this error but I don't have access to axios through that

@Dejan-Teofilovic
Copy link

I have very similar issue. How to fix it
Capture1
?
Capture

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests