我有以下index.js(node v19.6.0),带有调用外部API并注册webhook的POST请求。我正在注册的钩子的 url 已经可以工作并进行了测试。
我用谷歌搜索了该错误,但找不到任何结果。当我调用 /register/hook 方法时出现错误。它表明存在超时,但没有提供更多详细信息。问题是来自 API 提供商还是我进行 REST 调用的方式?
代码由Alchemy生成。
const express = require('express');
const app = express();
const port = 8080;
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
app.post("/register/hook", (req, res) => {
const options = {
method: 'POST',
headers: {
accept: 'application/json',
'X-Alchemy-Token': 'abc...def',
'content-type': 'application/json'
},
body: JSON.stringify({
AddressWebhookParams: {addresses: ['0xe592427a0aece92de3edee1f18e0157c05861564']},
url: 'https://webhook.site/dfb04cab-8ca9-40f1-a522-66918d4a7015',
type: 'ADDRESS_ACTIVITY'
})
};
fetch('https://alchemy-sdk-core-example.com/create-webhook', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
})
这是错误:
TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:12789:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
cause: ConnectTimeoutError: Connect Timeout Error
at onConnectTimeout (node:internal/deps/undici/undici:8236:28)
at node:internal/deps/undici/undici:8194:50
at Immediate._onImmediate (node:internal/deps/undici/undici:8225:13)
at process.processImmediate (node:internal/timers:475:21) {
code: 'UND_ERR_CONNECT_TIMEOUT'
}
}
[1]: https://docs.alchemy.com/reference/sdk-create-webhook
我通过添加修复了它
import { fetch, setGlobalDispatcher, Agent } from 'undici'
...
setGlobalDispatcher(new Agent({ connect: { timeout: 60_000 } }) )
在我的
fetch
配置超时之前。当然你应该先安装undici
仔细检查网址和参数,其他一切似乎都很好。如果 url 不存在或者服务器暂时关闭,通常会出现超时问题。 我也推荐使用 axios。它可以避免您设置额外的内容标题等麻烦。
如果您不从处理程序发回响应,客户端将无限期地等待,或者直到放弃:
fetch('https://alchemy-sdk-core-example.com/create-webhook', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err))
.finally(() => res.end()); // end the response process
更多信息这里。
我什么也没做。我刚刚切换到 WiFi。 :)