首页 > 解决方案 > 在 TypeScript 中未定义 axios

问题描述

我的 axios 导入有问题。在我的 TypeScript 中,我像这样导入它:

import axios from 'axios';

但是一旦我想使用axios,就会返回以下错误:

TypeError:无法读取未定义的属性“默认”

这就是我想使用 axios 的方式:

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

const ac = axios.create(config);

axios 版本是0.18.0

似乎模块并没有真正导出default Axios;

我花了最后几个小时在谷歌上搜索并尝试修复它,但我发现的只是"allowSyntheticDefaultImports": true在我的 tsconfig 的 compilerOptions 中设置。

我还查看了 axios.js 并发现了以下几行:

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

简而言之,我完全不知道我做错了什么,并希望得到任何帮助。如果您需要其他代码或信息,请告诉我,我会尽力提供信息。

先感谢您!

标签: javascripttypescriptaxios

解决方案


这篇文章的答案可以帮助您解决Axios POST 没有在 NodeJS/Express Route 中运行

基本上我在那里发布了一个 es6 axios 类,您可以通过以下方式导入:

npm i @eneto/es6-axios-class

or

npm i es6-axios-class

你可以在这里找到一个非常完整的例子: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> {
    }
}

推荐阅读