javascript - 在 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;
简而言之,我完全不知道我做错了什么,并希望得到任何帮助。如果您需要其他代码或信息,请告诉我,我会尽力提供信息。
先感谢您!
解决方案
这篇文章的答案可以帮助您解决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> {
}
}
推荐阅读
- hyperledger-fabric - 以byfn为例,Fabric cli如何获取peer/orderer的ip?
- android - 为什么我们不应该改变 TextView#getText() 返回值的内容?
- php - 如何将时间变量输出到我的时区?
- gitlab - 我可以在 Gitlab 中将两个独立的 maven 项目添加到一个项目中吗
- git - Symfony4 - 存储上传文件的好习惯
- forms - 如何在 xamarin 表单的 Flex 布局中从头开始对齐项目?
- c - 关于 dma_sync_single_for_cpu() / dma_sync_single_for_device() 的问题
- php - 如何获取这种类型的数组格式
- python - Beautiful Soup4 'NoneType' 对象没有属性 'text' 错误
- apache-spark - 使用 Spark 如何在末尾添加列