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

使用node-fetch获取Canvas API数据无法推送至Discord webhook如何解决

问题原因与修复方案

存在以下3个核心错误:

  • Promise链式调用逻辑错误:.then()需要传入函数作为回调,你直接写了fetch(...)会导致Discord请求在Canvas API发起时就立即执行,不会等待Canvas数据返回,执行顺序完全不符合预期。
  • POST请求体未序列化:node-fetch不会自动将JS对象转为JSON字符串,你直接把{content: 'hello world'}传给body,请求格式不符合Discord webhook要求,会被直接拒收。
  • 数据传递断层:处理Canvas返回数据的回调没有return任何值,如果你后续需要把Canvas获取到的内容推送到Discord,无法把数据传递到后续的调用环节。

修正后的代码

fetch(url + `courses/${course}/discussion_topics` , {
    method: "GET",
    headers : {
        'Authorization' : 'Bearer <auth token>',
        'Content-Type' : 'application/json'
    }
})
.then(res => res.json())
.then(data => { 
    console.log(data[0].id);
    console.log(data[0].title);
    console.log(data[0].message);
    // 如果要推送Canvas的数据,这里return出去给下一个then调用
    return data[0];
})
.then(canvasData => {
    // 把fetch包裹在函数回调内,等待前面请求完成后再执行
    return fetch("https://discord.com/api/webhooks/893327519103746149/<webhooktoken>", {
        method: "POST",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        // 手动序列化请求体
        body: JSON.stringify({
            // 不需要推送Canvas数据的话直接写成 content: 'hello world' 即可
            content: `新讨论:${canvasData.title}\n${canvasData.message}`
        })
    })
})
.catch(err => console.log(err))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:45:03