使用Telegram Bot API JavaScript发送文档遇Bad Request错误求助
解决Telegram Bot API发送文档时"Bad Request: there is no document in the request"错误
问题根源
- 手动设置的
accept: "application/json"请求头干扰了FormData的自动请求头生成,Telegram服务器无法正确解析表单中的文件数据 - 对
fs.readFileSync的返回值做了多余的Buffer转换,该方法本身就返回Buffer对象,重复转换可能破坏文件结构 - 部分环境下需要明确指定文件的Content-Type,才能让服务器正确识别文件类型
修正后的代码
const FILE_PATH = path.join(__dirname, "test.txt"); // 直接获取文件Buffer,无需二次转换 const fileBuffer = fs.readFileSync(FILE_PATH); const formData = new FormData(); formData.append("chat_id", CHAT_ID); // 明确指定文件的Content-Type,提升跨环境兼容性 formData.append("document", fileBuffer, { filename: "test.txt", contentType: "text/plain" // 根据文件类型调整,如xlsx用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,zip用application/zip }); formData.append("caption", "Document title or description here"); const telegram_sendmessage = await fetch( `https://api.telegram.org/${BOT_TOKEN}/sendDocument`, { method: "POST", // 移除手动设置的accept头,让fetch自动处理FormData的请求头 body: formData, } ); const response = await telegram_sendmessage.json(); console.log(response);
额外注意事项
- 确认
CHAT_ID和BOT_TOKEN参数无拼写错误 - 根据文件类型匹配正确的
contentType值,避免服务器无法识别文件 - 提前用
fs.existsSync(FILE_PATH)校验文件路径是否有效,确保能读取到目标文件
内容的提问来源于stack exchange,提问作者Amine Deflaoui
相关产品推荐
相关产品推荐

