调用axios.get时报Uncaught TypeError错误 无返回数据如何解决?
错误原因及修复方案
1 核心报错Uncaught TypeError: axios.get(...) is not a function解决
- 先确认axios依赖已安装,执行命令:
npm install axios - 检查axios导入语句:
- 如果是CommonJS规范(Node.js默认模块化方案),必须写:
const axios = require('axios').default,漏写.default会直接触发该报错 - 如果是ES Module规范,必须写:
import axios from 'axios',不要使用import * as axios from 'axios'的写法
- 如果是CommonJS规范(Node.js默认模块化方案),必须写:
2 其他代码逻辑问题修复
- 现有URI中的
[uid]、[msg]为占位符,需要替换为实际的用户唯一标识和用户发送的消息内容,否则接口会返回参数错误 message.channel.stopTyping()现在写在axios请求外侧,请求还未返回就会提前结束输入状态,需要移入请求回调中- 直接返回整个
response对象会导致回复内容异常,需要取接口实际返回的response.data - setTimeout内部的异步代码不会被外层try/catch捕获,需要单独加异常处理
修复后参考代码
const axios = require('axios').default; // CommonJS规范写法,用ES Module就换成对应导入语句 bot.on("message", async function(message) { try { if (message.author == bot.user) return; if (message.channel.type == "dm" || message.channel.type == "group") { await new Promise(resolve => setTimeout(resolve, 3000)); if (!message.channel.typing) { message.channel.startTyping(); setTimeout(async function() { try { // 替换占位符为实际参数 const URI = `http://api.brainshop.ai/get?bid=你的实际bid&key=你的实际key&uid=${message.author.id}&msg=${encodeURIComponent(message.content)}`; const response = await axios.get(URI); message.reply(response.data); } catch (err) { console.log('请求错误:', err); message.reply('请求失败,请稍后重试'); } finally { message.channel.stopTyping(); } }, 5000); } } } catch (e) { console.log(e) } });
内容的提问来源于stack exchange,提问作者SCPF
相关产品推荐
相关产品推荐

