# @achingbrain/electron-fetch 中文文档

规范地址：https://npmcn.com/package/%40achingbrain/electron-fetch/

版本：1\.7\.2
npm 元数据更新时间：2022-04-04T11:10:58.758Z
中文译文更新时间：2026-11-06T14:20:39.030Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40achingbrain/electron-fetch
原文对照：https://npmcn.com/package/%40achingbrain/electron-fetch/?lang=original
项目主页：https://github.com/arantes555/electron-fetch
源码仓库：https://github.com/arantes555/electron-fetch

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：112 kB，7 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=6
- 运行依赖：1 个
- 首次发布：2020-10-09T13:48:47.550Z
- 最新版本发布：2020-10-09T13:48:47.760Z
- 近 30 天下载量：2999（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：1（近 12 个月 0 个）

## 中文简介

一个带出窗口的轻量级模块. 获取到电子的背景过程

## 安装

```sh
npm install @achingbrain/electron-fetch
```

也可以使用：`pnpm add @achingbrain/electron-fetch`、`yarn add @achingbrain/electron-fetch`、`bun add @achingbrain/electron-fetch`

## README

# 电子牵引

[![npm version](https://img.shields.io/npm/v/electron-fetch.svg?style=flat-square)](https://www.npmjs.com/package/electron-fetch) [![build status](https://img.shields.io/travis/arantes555/electron-fetch.svg?style=flat-square)](https://travis-ci.org/arantes555/electron-fetch) [![coverage status](https://img.shields.io/codecov/c/github/arantes555/electron-fetch.svg?style=flat-square)](https://codecov.io/gh/arantes555/electron-fetch)

一个能带来 `window.fetch` 到Electron的背景过程. 从 [`node-fetch`](https://github.com/bitinn/node-fetch)。 。 。 .

## 动机

而不是执行 `XMLHttpRequest` 在电上 `net` 运行特定浏览器的模块 [获取多填充](https://github.com/github/fetch),为什么不从本地去 `net.request` 改为 `fetch` API直接吗? ┮ `electron-fetch`,最小代码 `window.fetch` 兼容 Electron 的背景运行时间的 API.

为什么不直接使用节点比对? 嗯,电能 `net` 模块比 Node.js 更好的工作 `http` 模块.

## 特征

-   保持与 `window.fetch` API (英语).
-   使用 Electron 或 electron 或 Node.js 运行 `net` 模块,或节点.js `http` 模块作为后端.
-   跟踪时自觉权衡 [是什么wg 获取光谱](https://fetch.spec.whatwg.org/) 财务报告和审定财务报表 [流谱](https://streams.spec.whatwg.org/) 执行细节,已知差异的文件.
-   用本地之约.
-   根据请求和答复,使用本地流取为体.
-   正确解码内容编码( gzip/ deflate),并转换字符串输出( 例如) `res.text()` 财务报告和审定财务报表 `res.json()`)自动到UTF-8.
-   有用的扩展,如超时,重定向限制(当运行于Node.js上时),响应大小限制,\[解释错误\]\[\]用于排除出错.

## 客户端获取的差异

-   见 [已知差异](https://github.com/arantes555/electron-fetch/blob/master/LIMITS.md) 详细情况.
-   如果你碰巧使用一个缺失的特性 `window.fetch` 提供,可以随意打开一个问题.
-   拉请求也欢迎!

## 与节点比对的差异

-   删除了节点比对特定选项, 如 `compression`。 。 。 .
-   添加特定电子选项以指定 `Session` 启用其中的 cookie( t) .
-   添加特定电子选项 `useElectronNet`,在运行 Electron 时可以设定为虚假,以表现为 Node.js.
-   取消使用自定义 承诺执行(2018年), `Promise` 到处都有!).
-   取消了禁止内容压缩的可能性(与 Electron 兼容) `net` 和兴趣有限))
-   [`standard`\- 已实现](http://standardjs.com/) 密码.

## 安装

```sh
$ npm install electron-fetch --save
```

## 使用量

```javascript
import fetch from 'electron-fetch'
// or
// const fetch = require('electron-fetch').default

// plain text or html

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

// json

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

// catching network error
// 3xx-5xx responses are NOT network errors, and should be handled in then()
// you only need one catch() at the end of your promise chain

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

// stream
// the node.js way is to use stream when possible

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

// buffer
// if you prefer to cache binary data in full, use buffer()
// note that buffer() is a electron-fetch only API

import fileType from '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'))
    })

// post

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

// post with stream from file

import { createReadStream } from 'fs'

const stream = createReadStream('input.txt')
fetch('http://httpbin.org/post', { method: 'POST', body: stream })
    .then(res => res.json())
    .then(json => console.log(json))

// post with JSON

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

// post with form-data (detect multipart)

import FormData from 'form-data'

const form = new FormData()
form.append('a', 1)
fetch('http://httpbin.org/post', { method: 'POST', body: form })
    .then(res => res.json())
    .then(json => console.log(json))

// post with form-data (custom headers)
// note that getHeaders() is non-standard API

import FormData from 'form-data'

const form = new FormData()
form.append('a', 1)
fetch('http://httpbin.org/post', { method: 'POST', body: form, headers: form.getHeaders() })
    .then(res => res.json())
    .then(json => console.log(json))

// node 7+ with async function

(async function () {
    const res = await fetch('https://api.github.com/users/github')
    const json = await res.json()
    console.log(json)
})()
```

见 [测试案例](https://github.com/arantes555/electron-fetch/blob/master/test/test.js) 需要更多的实例.

## API 密码

### 获取( url\[, 选项\])

-   `url` 用于获取的 URL 的字符串
-   `options` [选项](https://npmcn.com/package/%40achingbrain/electron-fetch/#readme-fetch-options) 用于 HTTP( S) 请求
-   回返情况: `Promise<[Response](https://npmcn.com/package/%40achingbrain/electron-fetch/#readme-class-response)>`

执行 HTTP( S) 获取 .

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

#### 选项

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

```js
const defaultOptions = {
    // 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', // (/!\ only works when running on Node.js) set to `manual` to extract redirect headers, `error` to reject redirect
    signal: null,       // the AbortSignal from an AbortController instance.

    // The following properties are electron-fetch extensions
    follow: 20,         // (/!\ only works when running on Node.js) 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)
    size: 0,            // maximum response body size in bytes. 0 to disable
    session: session.defaultSession, // (/!\ only works when running on Electron) Electron Session object.,
    agent: null,        // (/!\ only works when useElectronNet is false) Node HTTP Agent.,
    useElectronNet: true, // When running on Electron, defaults to true. On Node.js, defaults to false and cannot be set to true.
    useSessionCookies: true, // (/!\ only works when running on Electron >= 7) Whether or not to automatically send cookies from session.,
    user: undefined,    // When running on Electron behind an authenticated HTTP proxy, username to use to authenticate
    password: undefined // When running on Electron behind an authenticated HTTP proxy, password to use to authenticate
}
```

##### 默认信头

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

| 页眉 | 数值 |
| --- | --- |
| `Accept-Encoding` | `gzip,deflate` |
| `Accept` | `*/*` |
| `Connection` | `close` |
| `Content-Length` | _(如有可能,自动计算)_ |
| `User-Agent` | `electron-fetch/1.0 (+https://github.com/arantes555/electron-fetch)` |

### 类: 请求

HTTP( S) 请求, 包含关于 URL 、 方法、 标题和 机构 的信息 。 此类执行 [体质](https://npmcn.com/package/%40achingbrain/electron-fetch/#readme-iface-body) 接口.

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

-   `type`
-   `destination`
-   `referrer`
-   `referrerPolicy`
-   `mode`
-   `credentials`
-   `cache`
-   `integrity`
-   `keepalive`

提供了以下电子-牵引扩展特性:

-   `follow` (/!\\只在节点上运行时工作)
-   `counter` (/!\\只在节点上运行时工作)
-   `session` (/!\\只在运行电子时工作)
-   `agent` (/!\\只在节点上运行时工作)
-   `useElectronNet` (/!\\只在电子上运行时工作,在节点上设定为真实时投掷)
-   `useSessionCookies` (/!\\ 只在Electron上运行时工作 \\ 7)

见 [选项](https://npmcn.com/package/%40achingbrain/electron-fetch/#readme-fetch-options) 用于这些扩展的确切含义.

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

_(符合规格)_

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

构造一个新的 `Request` 对象。 构造器与 [浏览器](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request)。 。 。 .

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

### 类别:回应

HTTP( S) 响应 。 此类执行 [体质](https://npmcn.com/package/%40achingbrain/electron-fetch/#readme-iface-body) 接口.

此时电子牵引中未执行以下属性:

-   `Response.error()`
-   `Response.redirect()`
-   `type`
-   `redirected`
-   `trailer`

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

_(符合规格)_

-   `body` 字符串或 [可读流](https://nodejs.org/api/stream.html#stream_readable_streams)
-   `options` A 类 [`ResponseInit`](https://fetch.spec.whatwg.org/#responseinit) 选项词典

构造一个新的 `Response` 对象。 构造器与 [浏览器](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response)。 。 。 .

由于Node.js & Electron的背景不执行服务工人(为这个班级设计),人们很少需要建造一个 `Response` 直接说.

### 类: 页眉

此类允许在一组HTTP头上进行操纵并活化. 《公约》中规定的所有方法 [获取标准](https://fetch.spec.whatwg.org/) 已执行.

#### 新标题( \[init\] )

_(符合规格)_

-   `init` 预填的可选参数 `Headers` 对象

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

```js
// 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 的缩写)_

-   节点.js [`Readable` 流线](https://nodejs.org/api/stream.html#stream_readable_streams)

包含在 `Body` 对象。 请注意,虽然 [获取标准](https://fetch.spec.whatwg.org/) 要求财产永远是一个WhatWG `ReadableStream`,在电子牵引中,它是一个节点.js [`Readable` 流线](https://nodejs.org/api/stream.html#stream_readable_streams)。 。 。 .

#### 躯体

_(符合规格)_

-   `Boolean`

如果这个尸体被消耗了,那么它就会被埋藏起来 按光谱,一个被消耗的身体不能再被使用.

#### 车体. 阵列缓冲 ()

#### 机构. blob( )

#### 机构.json()

#### 文本( )

_(符合规格)_

-   回返情况: `Promise`

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

#### 弹出器( )

_(electron-fatch 扩展名)_

-   回返情况: `Promise<Buffer>`

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

#### 文体. 文本转换( )

_(electron-fatch 扩展名)_

-   回返情况: `Promise<String>`

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

### 类: 获取错误

_(electron-fatch 扩展名)_

获取过程中的操作错误 。 见 [错误的修复(MD)](https://github.com/arantes555/electron-fetch/blob/master/ERROR-HANDLING.md) 需要更多信息.

## 许可证

麻省理工学院

## 致谢

感谢 [gi/牵引](https://github.com/github/fetch) 提供坚实的执行参考. 感谢 [节点比对](https://github.com/bitinn/node-fetch) 为叉提供坚实基础.

## 常见问题

### @achingbrain/electron-fetch 是什么？

一个带出窗口的轻量级模块\. 获取到电子的背景过程

### 如何安装 @achingbrain/electron-fetch？

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

### @achingbrain/electron-fetch 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @achingbrain/electron-fetch 支持 ESM 还是 CommonJS？

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

### @achingbrain/electron-fetch 需要什么版本的 Node\.js？

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

### @achingbrain/electron-fetch 可以商用吗？

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

### @achingbrain/electron-fetch 的下载量有多少？

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

### @achingbrain/electron-fetch 还在维护吗？

最新版本 1\.7\.2 发布于 2020/10/09（6 年前）；至今共发布 1 个版本，其中过去 12 个月发布了 0 个；首次发布于 2020/10/09。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

