Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

axios undefined in TypeScript

I am having trouble with my axios import. In my TypeScript, I am importing it like this:

import axios from 'axios';

But as soon as I want to use axios, the following error is returned:

TypeError: Cannot read property 'default' of undefined

This is how I want to use axios:

const config = {
        baseURL: 'https://git.something.net/api/v4',
        headers: {'PRIVATE-TOKEN': 'IAMNOTTELLINGYOUTHIS'},
    }

const ac = axios.create(config);

axios version is 0.18.0

Seems like the module is not really exporting the default Axios;

I have spent the last hours googeling and trying to fix it, but all I found was setting "allowSyntheticDefaultImports": true in the compilerOptions of my tsconfig.

I also had a peek at the axios.js and found these lines:

// Allow use of default import syntax in TypeScript
module.exports.default = axios;

To keep it short, I have absolutely no clue what I am doing wrong and would appreciate any help. If you need additional code or info, just let me know and I will try to provide the information.

Thank you in advance!

like image 785
user2240265 Avatar asked Feb 02 '26 20:02

user2240265


1 Answers

the answare from this post can help you out Axios POST isn't running inside NodeJS/Express Route

basically I posted there an es6 axios class that you can import by:

npm i @eneto/es6-axios-class

or

npm i es6-axios-class

you can find a very complete example here: https://github.com/EnetoJara/axios-typescript/blob/master/examples/userApi.ts

import { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import { Api } from './../src/api/api';
import { Credentials, Token, User } from './interfaces';

export class UserApi extends Api {
    public constructor (config?: AxiosRequestConfig) {
        super(config);


        // this middleware is been called right before the http request is made.
        this.interceptors.request.use((param: AxiosRequestConfig) => ({
            ...param,
        }));

        // this middleware is been called right before the response is get it by the method that triggers the request
        this.interceptors.response.use((param: AxiosResponse) => ({
            ...param
        }));

        this.userLogin = this.userLogin.bind(this);
        this.userRegister = this.userRegister.bind(this);
        this.getAllUsers = this.getAllUsers.bind(this);
        this.getById = this.getById.bind(this);
    }

    public userLogin (credentials: Credentials): Promise<Token> {
    }

    public userRegister (user: User): Promise<number> {
    }

    public async getAllUsers (): Promise<User[]> {
    }

    public getById (id: number): Promise<User> {
    }
}
like image 139
Ernesto Avatar answered Feb 05 '26 10:02

Ernesto