跳到主要内容

2 篇博文 含有标签「node-fetch」

查看所有标签

从 node-fetch 的响应中获取 readable

· 阅读需 1 分钟
1adybug
子虚伊人

node-fetchresponse.body 虽然类型标记为 ReadableStream,但实际上并不是,被 Readable.fromweb 调用时会报错,此时改为使用 Readable.from 即可成功。

import fetch from "node-fetch"

const response = await fetch("http://somewhere.com")

// ❌ 会报错
const readable = Readable.fromweb(response.body!)

// ✅ 不会报错
const readable = Readable.from(response.body!)

在 Node.js 中为 fetch 配置代理

· 阅读需 1 分钟
1adybug
子虚伊人

Node.js 中,原生的 fetch API 并不直接支持代理功能。可以使用 node-fetch 库和 https-proxy-agent 库来实现通过代理服务器发送请求的功能:

import { HttpsProxyAgent } from "https-proxy-agent"
import fetch from "node-fetch"

// 代理服务器的URL
const proxyUrl = "http://your-proxy-server:port"

// 目标URL,即你想要通过代理服务器访问的URL
const targetUrl = "http://example.com"

// 配置代理服务器
const proxyAgent = new HttpsProxyAgent(proxyUrl)

// 使用fetch发起请求,通过代理服务器访问目标URL
fetch(targetUrl, { agent: proxyAgent })
注意

与原生的 fetch 不同,node-fetchresponse.json() 返回值类型为 Promise<unknown>