Node.js中如何向Discord Webhook发消息?遇fetch报错求解
node-fetch 使用问题解决方法
遇到的问题
- 使用
require导入node-fetch时触发错误:
const fetch = require("node-fetch") ^ Error [ERR_REQUIRE_ESM]: require() of ES Module /home/runner/chat/node_modules/node-fetch/src/index.js from /home/runner/chat/index.js not supported. Instead change the require of /home/runner/chat/node_modules/node-fetch/src/index.js in /home/runner/chat/index.js to a dynamic import() which is available in all CommonJS modules. at Object.<anonymous> (/home/runner/chat/index.js:15:15) { code: 'ERR_REQUIRE_ESM' }
- 改用动态
import后,提示fetch is not a function,对应错误代码:
const fetch = import("node-fetch"); fetch(process.env.WEBHOOK, { 'method': 'POST', 'body': { 'username': json.username, "content": json.message} }).then(res=> console.log(res)).catch(err => console.error(err));
解决方法
node-fetch v3及以上版本是纯ES模块,不支持CommonJS的require导入,需按以下方式处理:
方案1:在CommonJS文件中使用动态import
动态import()返回的是Promise,需先获取模块的默认导出(fetch),同时注意body需序列化为JSON字符串并设置请求头:
// 方式A:async/await写法 async function sendWebhook() { const { default: fetch } = await import("node-fetch"); try { const res = await fetch(process.env.WEBHOOK, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: json.username, content: json.message }) }); console.log(res); } catch (err) { console.error(err); } } sendWebhook(); // 方式B:链式调用写法 import("node-fetch").then(({ default: fetch }) => { fetch(process.env.WEBHOOK, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: json.username, content: json.message }) }).then(res => console.log(res)).catch(err => console.error(err)); });
方案2:切换为ES模块
在项目的package.json中添加"type": "module",之后即可使用静态import:
import fetch from "node-fetch"; fetch(process.env.WEBHOOK, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: json.username, content: json.message }) }).then(res => console.log(res)).catch(err => console.error(err));
错误原因说明
require报错:node-fetch v3+放弃了CommonJS支持,强制使用ES模块规范。fetch is not a function:动态import()返回Promise而非直接的fetch函数,需解构获取默认导出。- 额外问题:原代码中直接传对象给
body无效,fetch不会自动序列化对象,必须转为JSON字符串并设置Content-Type: application/json头。
内容的提问来源于stack exchange,提问作者vlone
相关产品推荐
相关产品推荐

