当我使用 fetch 从 Node.js 向外部 API 发出请求时,我最终会等到超时。但是,当我使用curl 直接从命令行尝试相同的请求时,它有效。
获取请求: 数据对象肯定没问题
await fetch(EXTERNAL_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data,
})
.then((response) => {
return response.json();
})
.then(async (data: any) => {
// treatment
}));
卷曲呼叫:
curl -X POST 'EXTERNAL_API' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=XXX' \
-d 'scope=XXX' \
-d 'redirect_uri=XXX' \
-d 'client_id=XXX' \
-d 'client_secret=XXX' \
-d 'code=XXX'
我尝试添加node-fetch来发出请求,并检查了Ubuntu服务器(22.04)的配置,但没有任何效果;还是不行。
事实证明,这确实是服务器配置问题,特别是代理问题。 Curl 与环境变量中定义的代理一起使用。因此,我检索了此代理并尝试将其添加到我的 Node.js 请求中。
代码现在看起来像这样:
import { RequestInfo, RequestInit } from 'node-fetch';
import { HttpsProxyAgent } from 'https-proxy-agent';
const fetch = (url: RequestInfo, init?: RequestInit) => import('node-fetch').then(({ default: fetch }) => fetch(url, init));
const proxyAgent = new HttpsProxyAgent(HTTPS_PROXY);
[...]
await fetch(EXTERNAL_URL, {
agent: proxyAgent,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data,
})
.then((response) => {
return response.json();
})
.then(async (data: any) => {/*treatment*/});
问题是由于我的 Ubuntu 服务器运行的网络导致的,这需要通过代理。