@achingbrain/node-fetch

中文文档
2.6.7发布于 2021/06/19MITESM + CJS零依赖近 30 天下载 3.9万

一个带出窗口的轻量级模块. 获取到节点.js

中文使用文档
文档目录18 节
  1. 动机
  2. 特征
  3. 客户端获取的差异
  4. 安装
  5. 装入和配置模块
  6. 常见用途
  7. 高级使用
  8. API 密码
  9. 获取( url[, 选项])
  10. 选项
  11. 类: 请求
  12. 类别:回应
  13. 类: 页眉
  14. 接口:正文
  15. 类: 获取错误
  16. 类: 中止错误
  17. 致谢
  18. 许可证

临时叉

这是临时的节点叉 与固定从 节点牵引# 1172 合并。 它将不予更新或维护.

节点比对

npm version build status coverage status install size Discord

一个能带来 window.fetch 到节点.js

(我们正在寻找) v2 维护者和协作者(中文(简体) )

Backers

动机

而不是执行 XMLHttpRequest 在节点.js中运行特定浏览器 获取多填充,为什么不从本地去 http 改为 fetch API直接吗? 因此, node-fetch,最小代码 window.fetch 在 Node.js 运行时间上兼容 API.

看马特安德鲁斯 同位素比对 或者莱昂纳多·克萨达的 横切 同位素用途(出口) node-fetch 用于服务器侧, whatwg-fetch 客户端).

特征

  • 保持与 window.fetch API (英语).
  • 跟踪时自觉权衡 WhatWG 获取光谱 财务报告和审定财务报表 流谱 实施细节,记录已知差异.
  • 使用本地承诺, 但允许用[插入您最喜欢的承诺库] 替换它 .
  • 在请求和响应时使用本地的节点流作为正文 .
  • 正确解码内容编码( gzip/ deflate)并转换字符串输出( 例如) res.text() 财务报告和审定财务报表 res.json())自动到UTF-8.
  • 有用的扩展,如超时,重定向限制,响应大小限制, 明显错误 解决麻烦.

客户端获取的差异

  • 见 已知差异 详细情况.
  • 如果你碰巧使用一个缺失的特性 window.fetch 提供,可以随意打开一个问题.
  • 拉请求也欢迎!

安装

目前稳定的释放量2.x(中文(简体) )

$ npm install node-fetch

装入和配置模块

我们建议你把舱载通过 require 在节点稳定ES模块之前:

const fetch = require('node-fetch');

如果您使用“承诺”图书馆而非本地图书馆,请通过 fetch.Promise数字 :

const Bluebird = require('bluebird');

fetch.Promise = Bluebird;

常见用途

注:以下文件为最新资料: 2.x 释放;见 1.x 读取我, (中文(简体) ), 更改日志 财务报告和审定财务报表 2.x 升级指南 对于差异.

纯文本或 HTML

fetch('https://github.com/')
    .then(res => res.text())
    .then(body => console.log(body));

贾森


fetch('https://api.github.com/users/github')
    .then(res => res.json())
    .then(json => console.log(json));

简单员额

fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' })
    .then(res => res.json()) // expecting a json response
    .then(json => console.log(json));

带 JSON 的帖子

const body = { a: 1 };

fetch('https://httpbin.org/post', {
        method: 'post',
        body:    JSON.stringify(body),
        headers: { 'Content-Type': 'application/json' },
    })
    .then(res => res.json())
    .then(json => console.log(json));

有窗体参数的帖子

URLSearchParams 从v7.5.0起,可在Node.js中查阅。 见 正式文件 对于更多的使用方法.

注: Content-Type 标题只自动设定为 x-www-form-urlencoded 当一个实例 URLSearchParams 规定如下:

const { URLSearchParams } = require('url');

const params = new URLSearchParams();
params.append('a', 1);

fetch('https://httpbin.org/post', { method: 'POST', body: params })
    .then(res => res.json())
    .then(json => console.log(json));

处理例外

注:3xxx-5xx的答复是: 没有 例外情况,应在 then(); 更多信息见下一节.

把捕捉物加到捕捉链上就能捕到 全部 例外,如出自节点核心库的错误,网络出错和操作出错,这些都是FriefError的例子. 见 错误处理文档 更多细节.

fetch('https://domain.invalid/')
    .catch(err => console.error(err));

处理客户端和服务器错误

常见的是创建帮助器功能来检查响应是否包含没有客户端(4xx)或服务器(5xx)错误响应:

function checkStatus(res) {
    if (res.ok) { // res.status >= 200 && res.status < 300
        return res;
    } else {
        throw MyCustomError(res.statusText);
    }
}

fetch('https://httpbin.org/status/400')
    .then(checkStatus)
    .then(res => console.log('will not get here...'))

高级使用

流线

"Node.js way"是在可能的情况下使用流:

fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
    .then(res => {
        const dest = fs.createWriteStream('./octocat.png');
        res.body.pipe(dest);
    });

在Node.js 14中,您也可以使用同步指示器读取 body不过,要小心抓住 错误——一个响应运行的时间越长,就越可能遇到错误.

const fetch = require('node-fetch');
const response = await fetch('https://httpbin.org/stream/3');
try {
    for await (const chunk of response.body) {
        console.dir(JSON.parse(chunk.toString()));
    }
} catch (err) {
    console.error(err.stack);
}

在Node.js 12中,您也可以使用同步延时器读取 body; 然而, 串行者与溪流 直到节点14才成熟,所以你需要做一些额外工作来确保你处理出错 直接从溪来 等待它的反应 完全关闭.

const fetch = require('node-fetch');
const read = async body => {
    let error;
    body.on('error', err => {
        error = err;
    });
    for await (const chunk of body) {
        console.dir(JSON.parse(chunk.toString()));
    }
    return new Promise((resolve, reject) => {
        body.on('close', () => {
            error ? reject(error) : resolve();
        });
    });
};
try {
    const response = await fetch('https://httpbin.org/stream/3');
    await read(response.body);
} catch (err) {
    console.error(err.stack);
}

缓冲

如果您喜欢全部缓存二进制数据,请使用缓冲 (). (注: buffer() 是一个 node-fetch- 仅限 API)

const fileType = require('file-type');

fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
    .then(res => res.buffer())
    .then(buffer => fileType(buffer))
    .then(type => { /* ... */ });

访问信头和其他 Meta 数据

fetch('https://github.com/')
    .then(res => {
        console.log(res.ok);
        console.log(res.status);
        console.log(res.statusText);
        console.log(res.headers.raw());
        console.log(res.headers.get('content-type'));
    });

与浏览器不同, 您可以访问原始 Set-Cookie 手动使用页眉 Headers.raw()。这是 node-fetch 仅限API.

fetch(url).then(res => {
    // returns an array of values, instead of a string of comma-separated values
    console.log(res.headers.raw()['set-cookie']);
});

使用文件流发送数据

const { createReadStream } = require('fs');

const stream = createReadStream('input.txt');

fetch('https://httpbin.org/post', { method: 'POST', body: stream })
    .then(res => res.json())
    .then(json => console.log(json));

带有窗体数据( 检测多部分) 的邮箱

const FormData = require('form-data');

const form = new FormData();
form.append('a', 1);

fetch('https://httpbin.org/post', { method: 'POST', body: form })
    .then(res => res.json())
    .then(json => console.log(json));

// OR, using custom headers
// NOTE: getHeaders() is non-standard API

const form = new FormData();
form.append('a', 1);

const options = {
    method: 'POST',
    body: form,
    headers: form.getHeaders()
}

fetch('https://httpbin.org/post', options)
    .then(res => res.json())
    .then(json => console.log(json));

请求取消终止符号

注:您只能取消节点QQv8.0.0上流出的请求

您可以取消请求 AbortController建议的执行是: abort-controller。 。 。 .

150毫秒后取消请求的一个实例如下:

import AbortController from 'abort-controller';

const controller = new AbortController();
const timeout = setTimeout(
  () => { controller.abort(); },
  150,
);

fetch(url, { signal: controller.signal })
  .then(res => res.json())
  .then(
    data => {
      useData(data)
    },
    err => {
      if (err.name === 'AbortError') {
        // request was aborted
      }
    },
  )
  .finally(() => {
    clearTimeout(timeout);
  });

见 测试案例 需要更多的实例.

API 密码

获取( url[, 选项])

  • url 用于获取的 URL 的字符串
  • options 选项 用于 HTTP( S) 请求
  • 回返情况: Promise<Response>

执行 HTTP( S) 获取 .

url 应该是一个绝对的url,例如 https://example.com/。路径相对的 URL (/file/under/root)或协议相对的 URL(//can-be-http-or-https.com/)将导致被拒绝 Promise。 。 。 .

选项

默认值在每个选项密钥后显示 .

{
    // These properties are part of the Fetch Standard
    method: 'GET',
    headers: {},        // request headers. format is the identical to that accepted by the Headers constructor (see below)
    body: null,         // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream
    redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect
    signal: null,       // pass an instance of AbortSignal to optionally abort requests

    // The following properties are node-fetch extensions
    follow: 20,         // maximum redirect count. 0 to not follow redirect
    timeout: 0,         // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.
    compress: true,     // support gzip/deflate content encoding. false to disable
    size: 0,            // maximum response body size in bytes. 0 to disable
    agent: null         // http(s).Agent instance or function that returns an instance (see below)
}
默认信头

如果没有设置值,则将自动发送下列请求头:

页眉数值
Accept-Encodinggzip,deflate (当 options.compress === true(中文(简体) )
Accept*/*
Connectionclose (无时) options.agent 已存在)
Content-Length(如有可能,自动计算)
Transfer-Encodingchunked (当 req.body 是一个溪流)
User-Agentnode-fetch/1.0 (+https://github.com/bitinn/node-fetch)

注:何时 body 是一个 Stream, (中文(简体) ), Content-Length 未自动设置.

自定义代理

这个 agent 选项允许您指定不属于“获取”范围的联网相关选项,包括但不限于以下选项:

  • 支持自签名证书
  • 只使用 IPv4 或 IPv6
  • 自定义 DNS 查询

见 http.Agent 更多信息.

此外 agent 选项接受返回的函数 http(s) 减少.Agent 实例为当前 網址,这在跨 HTTP 和 HTTPS 协议的重定向链中有用.

const httpAgent = new http.Agent({
    keepAlive: true
});
const httpsAgent = new https.Agent({
    keepAlive: true
});

const options = {
    agent: function (_parsedURL) {
        if (_parsedURL.protocol == 'http:') {
            return httpAgent;
        } else {
            return httpsAgent;
        }
    }
}

类: 请求

HTTP( S) 请求, 包含关于 URL 、 方法、 标题和 机构 的信息 。 此类执行 体质 接口.

由于节点(Node.js)的性质,目前尚未执行以下属性:

  • type
  • destination
  • referrer
  • referrerPolicy
  • mode
  • credentials
  • cache
  • integrity
  • keepalive

提供了以下节点扩展属性:

  • follow
  • compress
  • counter
  • agent

见 选项 用于这些扩展的确切含义.

新请求(输入[,选项])

(符合规格)

  • input 代表 URL 的字符串,或者另一个 Request (将被克隆)
  • options HTTP( S) 请求的[可选 [# fetch- options]

构造一个新的 Request 对象。 构造器与 浏览器。 。 。 .

在大多数情况下,直接 fetch(url, options) 简单于创建 Request 对象.

类别:回应

HTTP( S) 响应 。 此类执行 体质 接口.

此时节点不执行以下属性 :

  • Response.error()
  • Response.redirect()
  • type
  • trailer

新的反应([机构][,选项)])

(符合规格)

构造一个新的 Response 对象。 构造器与 浏览器。 。 。 .

由于Node.js不实施服务工人(为服务工人设计了这一类),人们很少需要建造一个 Response 直接说.

答复

(符合规格)

代表请求正常结束的方便财产。 如果答复情况大于或等于200,但小于300,将进行真实评价.

回复

(符合规格)

代表请求至少重新定向一次的方便财产。 如果内部重定向计数器大于0.

类: 页眉

此类允许在一组HTTP头上进行操纵并活化. 《公约》中规定的所有方法 获取标准 已执行.

新标题( [init] )

(符合规格)

  • init 预填的可选参数 Headers 对象

构造新 Headers 对象. init 也可以这样 null页:1 Headers 对象、键值映射对象或任何可移动对象.

// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class

const meta = {
  'Content-Type': 'text/xml',
  'Breaking-Bad': '<3'
};
const headers = new Headers(meta);

// The above is equivalent to
const meta = [
  [ 'Content-Type', 'text/xml' ],
  [ 'Breaking-Bad', '<3' ]
];
const headers = new Headers(meta);

// You can in fact use any iterable objects, like a Map or even another Headers
const meta = new Map();
meta.set('Content-Type', 'text/xml');
meta.set('Breaking-Bad', '<3');
const headers = new Headers(meta);
const copyOfHeaders = new Headers(headers);

接口:正文

Body 是一个抽象的界面,与两种方法都适用 Request 财务报告和审定财务报表 Response 课程.

此时节点尚未实施以下方法: 1

  • formData()

躯体

(来自 spec 的缩写)

数据封装在 Body 对象。 请注意,虽然 获取标准 要求财产永远是一个WhatWG ReadableStream在节点和节点之间 Readable 流线。 。 。 .

躯体

(符合规格)

  • Boolean

如果这具尸体被消耗了,那就意味着一个布尔的财产。 按照规格,一个被消耗的身体不能再被使用.

车体. 阵列缓冲 ()

机构. blob( )

机构.json()

文本( )

(符合规格)

  • 回返情况: Promise

将尸体收起来,并返回一个承诺,以决定其中的一种形式.

弹出器( )

(节点-牵引扩展)

  • 回返情况: Promise<Buffer>

收起尸体,把承诺还给缓冲器.

文体. 文本转换( )

(节点-牵引扩展)

  • 回返情况: Promise<String>

页:1 body.text(),除了不总是转换为UTF-8外,编码嗅觉将进行,如果可能,文本会转换为UTF-8.

(此 API 需要 npm 软件包的可选依赖性) 编码,需要手动安装. webpack 用户可能看到 一个警告信息 由于这种选择性依赖。 )

类: 获取错误

(节点-牵引扩展)

获取过程中的操作错误 。 见 错误的修复(MD) 需要更多信息.

类: 中止错误

(节点-牵引扩展)

请求因响应 AbortSignal是因为 abort 活动。 它有一个 name 财产 AbortError。见 (原始内容存档于2013-10-10). ERROR-HANDLING.MD 需要更多信息.

致谢

感谢 gi/牵引 提供坚实的执行参考.

node-fetch v1由下列人员维护: @ 比丁语; v2 由 @ TimothyGu (英语), (中文(简体) ), @ 比丁语 财务报告和审定财务报表 @jimmywarting (日语); v2 读取器由 @jkantr (英语)。 。 。 .

许可证

麻省理工学院

版本与发布记录

@achingbrain/node-fetch 共发布 6 个版本,首次发布于 2021/05/28;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.6.7latest2021/06/195 年前
2.6.62021/06/035 年前
2.6.52021/06/025 年前
2.6.42021/06/025 年前
2.6.32021/05/285 年前
2.6.22021/05/285 年前

关于 @achingbrain/node-fetch 的常见问题

@achingbrain/node-fetch 是什么?

一个带出窗口的轻量级模块. 获取到节点.js

如何安装 @achingbrain/node-fetch?

在项目目录运行 npm install @achingbrain/node-fetch,或使用 pnpm add / yarn add / bun add。

@achingbrain/node-fetch 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/achingbrain__node-fetch 是否存在。

@achingbrain/node-fetch 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@achingbrain/node-fetch 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js 4.x || >=6.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@achingbrain/node-fetch 可以商用吗?

@achingbrain/node-fetch 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@achingbrain/node-fetch 的下载量有多少?

根据 npm 官方下载统计,@achingbrain/node-fetch 在 2026/10/05 – 2026/11/03 这 30 天内被下载 39,284 次,日均约 1,309 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@achingbrain/node-fetch 还在维护吗?

最新版本 2.6.7 发布于 2021/06/19(5 年前);至今共发布 6 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/05/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。