You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中Axios简单get方法报错问题求助

为何这段Axios+TypeScript代码会报错?

错误核心

出现TypeError: Cannot read properties of undefined (reading 'get'),本质是你导入的axios对象为undefined,导致无法调用其get方法。结合你的tsconfig配置,问题出在TypeScript对CommonJS模块导出的处理逻辑与axios的导出结构不兼容。

解决办法

方法1:调整tsconfig.json配置

在compilerOptions中添加两个选项,让TypeScript正确识别CommonJS模块的默认导出:

{
  "compilerOptions": {
    "module": "CommonJS",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2017",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}

添加后,import axios from 'axios'就能正确获取到axios实例,无需修改代码。

方法2:改用CommonJS导入语法

直接使用Node.js原生的require语法,绕开TypeScript的导入适配问题:

const axios = require('axios');

axios.get('https://www.google.com').then((response) => {
    console.log(response.data);
});

方法3:重新安装axios依赖

如果之前安装过程中出现异常,可能导致依赖损坏,执行以下命令重新安装:

npm install axios
# 或使用yarn
yarn add axios

内容的提问来源于stack exchange,提问作者thamey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:15:44