电子牵引
一个能带来 window.fetch 到Electron的背景过程.
从 node-fetch。 。 。 .
动机
而不是执行 XMLHttpRequest 在电上 net 运行特定浏览器的模块 获取多填充,为什么不从本地去 net.request 改为 fetch API直接吗? ┮ electron-fetch,最小代码 window.fetch 兼容 Electron 的背景运行时间的 API.
为什么不直接使用节点比对? 嗯,电能 net 模块比 Node.js 更好的工作 http 模块.
特征
- 保持与
window.fetchAPI (英语). - 使用 Electron 或 electron 或 Node.js 运行
net模块,或节点.jshttp模块作为后端. - 跟踪时自觉权衡 是什么wg 获取光谱 财务报告和审定财务报表 流谱 执行细节,已知差异的文件.
- 用本地之约.
- 根据请求和答复,使用本地流取为体.
- 正确解码内容编码( gzip/ deflate),并转换字符串输出( 例如)
res.text()财务报告和审定财务报表res.json())自动到UTF-8. - 有用的扩展,如超时,重定向限制(当运行于Node.js上时),响应大小限制,[解释错误][]用于排除出错.
客户端获取的差异
- 见 已知差异 详细情况.
- 如果你碰巧使用一个缺失的特性
window.fetch提供,可以随意打开一个问题. - 拉请求也欢迎!
与节点比对的差异
- 删除了节点比对特定选项, 如
compression。 。 。 . - 添加特定电子选项以指定
Session启用其中的 cookie( t) . - 添加特定电子选项
useElectronNet,在运行 Electron 时可以设定为虚假,以表现为 Node.js. - 取消使用自定义 承诺执行(2018年),
Promise到处都有!). - 取消了禁止内容压缩的可能性(与 Electron 兼容)
net和兴趣有限)) standard- 已实现 密码.
安装
$ npm install electron-fetch --save
使用量
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)
})()
见 测试案例 需要更多的实例.
API 密码
获取( url[, 选项])
执行 HTTP( S) 获取 .
url 应该是一个绝对的url,例如 http://example.com/。路径相对的 URL (/file/under/root)或协议相对的 URL(//can-be-http-or-https.com/将会导致一个被否认的诺言.
选项
默认值在每个选项密钥后显示 .
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 、 方法、 标题和 机构 的信息 。 此类执行 体质 接口.
由于节点(Node.js)的性质,目前尚未执行以下属性:
typedestinationreferrerreferrerPolicymodecredentialscacheintegritykeepalive
提供了以下电子-牵引扩展特性:
follow(/!\只在节点上运行时工作)counter(/!\只在节点上运行时工作)session(/!\只在运行电子时工作)agent(/!\只在节点上运行时工作)useElectronNet(/!\只在电子上运行时工作,在节点上设定为真实时投掷)useSessionCookies(/!\ 只在Electron上运行时工作 \ 7)
见 选项 用于这些扩展的确切含义.
新请求(输入[,选项])
(符合规格)
input代表 URL 的字符串,或者另一个Request(将被克隆)optionsHTTP( S) 请求的[可选 [# fetch- options]
构造一个新的 Request 对象。 构造器与 浏览器。 。 。 .
在大多数情况下,直接 fetch(url, options) 简单于创建 Request 对象.
类别:回应
HTTP( S) 响应 。 此类执行 体质 接口.
此时电子牵引中未执行以下属性:
Response.error()Response.redirect()typeredirectedtrailer
新的反应([机构][,选项)])
(符合规格)
body字符串或 可读流optionsA 类ResponseInit选项词典
构造一个新的 Response 对象。 构造器与 浏览器。 。 。 .
由于Node.js & Electron的背景不执行服务工人(为这个班级设计),人们很少需要建造一个 Response 直接说.
类: 页眉
此类允许在一组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 的缩写)
- 节点.js
Readable流线
包含在 Body 对象。 请注意,虽然 获取标准 要求财产永远是一个WhatWG ReadableStream,在电子牵引中,它是一个节点.js Readable 流线。 。 。 .
躯体
(符合规格)
Boolean
如果这个尸体被消耗了,那么它就会被埋藏起来 按光谱,一个被消耗的身体不能再被使用.
车体. 阵列缓冲 ()
机构. blob( )
机构.json()
文本( )
(符合规格)
- 回返情况:
Promise
将尸体收起来,并返回一个承诺,以决定其中的一种形式.
弹出器( )
(electron-fatch 扩展名)
- 回返情况:
Promise<Buffer>
收起尸体,把承诺还给缓冲器.
文体. 文本转换( )
(electron-fatch 扩展名)
- 回返情况:
Promise<String>
页:1 body.text(),除不总是转换为UTF-8外,如果可能的话,将进行编码嗅觉并被文本转换为UTF-8.
类: 获取错误
(electron-fatch 扩展名)
获取过程中的操作错误 。 见 错误的修复(MD) 需要更多信息.
许可证
麻省理工学院