首页 > 解决方案 > 从画布正确获取信息并通过带有 node-fetch 的 webhook 将信息发送到 discord 时出现问题

问题描述

因此,我尝试使用 GET 从画布的 api 发送数据并使用该信息并使用节点获取从同一端点发送 POST 到不和谐。我可以毫无问题地从画布接收数据,并且我控制台日志以确保我必须正确的数据,但我似乎无法获得任何不和谐的信息。我正在使用 discords webhooks,但我不知道哪里出错了。

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);
}
 ) 
  .then(fetch("https://discord.com/api/webhooks/893327519103746149/<webhooktoken>", {
    method: "post",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
   body: {content: 'hello world'}
    
}))
.catch(err => console.log(err))

});```

标签: javascriptnode.jspromisediscordfetch

解决方案


如评论中所述,以防万一您有一些错字或误解。

此外,你需要 JSON.stringyify 你的身体。

请尝试以下示例:

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);
  })
  .then(() =>
    fetch(
      "https://discord.com/api/webhooks/893327519103746149/<webhooktoken>",
      {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username: "Canvas-Bot",
          content: "hello world",
        }),
      }
    )
      .then(res => res.json())
      .then(data => {
        console.log({ data });
      })
  )
  .catch(err => console.log(err));

另一种方法是异步/等待。我认为它更清洁。

(async function main() {
  try {
    const res1 = await fetch(url + `courses/${course}/discussion_topics`, {
      method: "GET",
      headers: {
        Authorization: "Bearer <auth token>",
        "Content-Type": "application/json",
      },
    });
    const data1 = await res1.json();
    console.log(data1);

    const res2 = await fetch(
      "https://discord.com/api/webhooks/893327519103746149/<webhooktoken>",
      {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username: "Canvas-Bot",
          content: "hello world",
        }),
      }
    );

    const data2 = await res2.json();
    console.log(data2);
  } catch (err) {
    console.log(err);
  }
})();

推荐阅读