从 canvas 正确获取信息并使用 node-fetch 通过 webhook 将信息发送到 discord 时遇到问题

Having a problem properly getting information from canvas and sending information to discord through webhook with node-fetch

所以我尝试使用 GET 从 canvas 的 api 发送数据并使用该信息并使用节点提取从同一端点发送 POST 到不和谐。我可以毫无问题地从 canvas 接收数据,并且我控制日志以确保我必须正确的数据,但我似乎无法获得任何不一致的信息。我正在使用 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))

});```

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

此外,您需要 JSON.stringyify 您的 body。

请尝试以下示例:

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/await 中。我觉得比较干净

(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);
  }
})();