【问题标题】:axios undefined in TypeScript在 TypeScript 中未定义 axios
【发布时间】:2020-05-11 15:15:58
【问题描述】:

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

过去几个小时我一直在谷歌搜索并试图修复它,但我发现的只是在我的 tsconfig 的 compilerOptions 中设置了"allowSyntheticDefaultImports": true

我还查看了 axios.js 并发现了这些行:

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

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

提前谢谢你!

【问题讨论】:

  • 这有点奇怪,既然0.14版本,axios应该也完全支持typescript,应该有defaultexport定义。
  • 是的,我也是这么想的。我很困惑……
  • 在一个项目中我使用 react + typescript 和 "axios": "^0.18.0" 这就是我导入它的方式:import axios, { AxiosStatic, AxiosRequestConfig, AxiosPromise } from 'axios'; 这一切都像一个魅力
  • 尝试清除 npm 缓存并运行新的 npm 安装
  • 不幸的是,这没有帮助。做了一个npm cache clear --force,删除了node_modules文件夹,再次运行npm install,没有任何改变。也许需要额外的信息:我正在尝试开发一个火箭聊天应用程序,并且在打包和部署期间一切正常,但在执行期间失败。

标签: javascript typescript axios


【解决方案1】:

这篇文章的答案可以帮助你Axios POST isn't running inside 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> {
    }
}

【讨论】:

    猜你喜欢
    • 2020-03-05
    • 2017-09-27
    • 2020-10-24
    • 2019-12-18
    • 1970-01-01
    • 2018-12-11
    • 2018-01-12
    • 2021-07-31
    • 2019-03-30
    相关资源
    最近更新 更多