调用Discord API获取服务器频道时出现Failed to fetch错误求助
调用Discord API获取服务器频道列表时,出现Failed to fetch错误,但相同请求在Postman和C# RestSharp中可正常运行。获取公会列表的fetch代码能成功执行,仅获取频道的代码失败。
成功获取公会列表的代码:
var detectGuilds= async () => { const response = await fetch('https://discord.com/api/users/@me/guilds', { method: 'GET', headers: { 'Authorization': 'Bot myBotToken' } }); const result = await response.json(); }
失败的获取频道代码:
var detectChannels= async () => { var idSelectedGuild = dictGuilds[document.getElementById("comboGuilds").value]; var uri =`https://discord.com/api/guilds/${idSelectedGuild}/channels`; var uri2 ="https://discord.com/api/v10/guilds/94055174550578/channels" const response = await fetch(uri, { method: 'GET', headers: { 'Authorization': 'Bot myBotToken', //'User-Agent' : 'Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)' } }); const result = await response.json(); alert(result) }
错误信息:
Uncaught TypeError TypeError: Failed to fetch
at detectChannels (c:\Users\Moi\Downloads\test.html:173:28)
at onchange (c:\Users\Moi\Downloads\test.html:104:77)
--- await ---
at onchange (c:\Users\Moi\Downloads\test.html:104:77)
at handleMouseUp_ (undefined:586:32)
排查跨域(CORS)限制
浏览器fetch受同源策略约束,本地直接打开HTML文件(file://协议)发起请求时,Discord API的CORS规则会拦截该请求,而Postman和后端代码不受此限制。解决方式:- 用本地服务器(如
http-server)托管HTML文件,以http://协议访问,而非直接打开本地文件。
- 用本地服务器(如
校验API版本与URL准确性
统一使用指定版本的API地址(如v10),避免版本兼容问题:var uri =`https://discord.com/api/v10/guilds/${idSelectedGuild}/channels`;同时在代码中打印
idSelectedGuild和uri的值,确认公会ID有效、URL格式正确,排除空值或ID格式错误的情况。补充必要请求头
取消注释并添加User-Agent请求头,Discord API对请求头有明确要求,浏览器默认的User-Agent可能不符合规范:headers: { 'Authorization': 'Bot myBotToken', 'User-Agent': 'Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)' }捕获详细错误信息
给代码添加try-catch块,打印更具体的错误细节(如HTTP状态码、CORS报错),避免仅依赖通用的Failed to fetch提示:var detectChannels= async () => { try { var idSelectedGuild = dictGuilds[document.getElementById("comboGuilds").value]; console.log("公会ID:", idSelectedGuild); var uri =`https://discord.com/api/v10/guilds/${idSelectedGuild}/channels`; console.log("请求URL:", uri); const response = await fetch(uri, { method: 'GET', headers: { 'Authorization': 'Bot myBotToken', 'User-Agent': 'Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)' } }); if (!response.ok) { throw new Error(`HTTP错误!状态码: ${response.status}`); } const result = await response.json(); console.log(result); alert(JSON.stringify(result)); } catch (error) { console.error("Fetch错误详情:", error); alert("错误信息: " + error.message); } }确认Bot权限
检查Bot是否在目标公会中,且拥有View Channels等必要权限,确保Bot本身具备访问该公会频道的权限。
内容的提问来源于stack exchange,提问作者Exarilo

