net
使用 Chromium 的原生网络库发出 HTTP/HTTPS 请求
¥Issue HTTP/HTTPS requests using Chromium's native networking library
net
模块是用于发出 HTTP(S) 请求的客户端 API。它类似于 Node.js 的 HTTP 和 HTTPS 模块,但使用 Chromium 的原生网络库而不是 Node.js 实现,为 Web 代理提供更好的支持。它还支持检查网络状态。
¥The net
module is a client-side API for issuing HTTP(S) requests. It is
similar to the HTTP and
HTTPS modules of Node.js but uses
Chromium's native networking library instead of the Node.js implementation,
offering better support for web proxies. It also supports checking network status.
以下是你可以考虑使用 net
模块而不是原生 Node.js 模块的非详尽列表:
¥The following is a non-exhaustive list of why you may consider using the net
module instead of the native Node.js modules:
-
自动管理系统代理配置,支持 wpad 协议和代理 pac 配置文件。
¥Automatic management of system proxy configuration, support of the wpad protocol and proxy pac configuration files.
-
HTTPS 请求的自动隧道。
¥Automatic tunneling of HTTPS requests.
-
支持使用基本、摘要、NTLM、Kerberos 或协商身份验证方案对代理进行身份验证。
¥Support for authenticating proxies using basic, digest, NTLM, Kerberos or negotiate authentication schemes.
-
支持流量监控代理:类似 Fiddler 的代理用于访问控制和监控。
¥Support for traffic monitoring proxies: Fiddler-like proxies used for access control and monitoring.
API 组件(包括类、方法、属性和事件名称)与 Node.js 中使用的组件类似。
¥The API components (including classes, methods, properties and event names) are similar to those used in Node.js.
用法示例:
¥Example usage:
const { app } = require('electron')
app.whenReady().then(() => {
const { net } = require('electron')
const request = net.request('https://github.com')
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`)
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`)
})
response.on('end', () => {
console.log('No more data in response.')
})
})
request.end()
})
仅当应用发出 ready
事件后才能使用 net
API。尝试在 ready
事件之前使用该模块将引发错误。
¥The net
API can be used only after the application emits the ready
event.
Trying to use the module before the ready
event will throw an error.
方法
¥Methods
net
模块有以下方法:
¥The net
module has the following methods:
net.request(options)
¥Returns ClientRequest
使用提供的 options
创建一个 ClientRequest
实例,该实例直接转发到 ClientRequest
构造函数。net.request
方法将用于根据 options
对象中指定的协议方案发出安全和不安全的 HTTP 请求。
¥Creates a ClientRequest
instance using the provided
options
which are directly forwarded to the ClientRequest
constructor.
The net.request
method would be used to issue both secure and insecure HTTP
requests according to the specified protocol scheme in the options
object.
net.fetch(input[, init])
-
input
字符串 | GlobalRequest¥
input
string | GlobalRequest -
init
RequestInit & {绕过 CustomProtocolHandlers?:boolean } (optional)¥
init
RequestInit & { bypassCustomProtocolHandlers?: boolean } (optional)
返回 Promise<GlobalResponse>
- 见 响应。
¥Returns Promise<GlobalResponse>
- see Response.
使用 Chrome 的网络堆栈发送请求,类似于 fetch()
在渲染器中的工作方式。这与 Node 的 fetch()
不同,后者使用 Node.js 的 HTTP 堆栈。
¥Sends a request, similarly to how fetch()
works in the renderer, using
Chrome's network stack. This differs from Node's fetch()
, which uses
Node.js's HTTP stack.
示例:
¥Example:
async function example () {
const response = await net.fetch('https://my.app')
if (response.ok) {
const body = await response.json()
// ... use the result.
}
}
此方法将从 默认会话 发出请求。要从另一个会话发送 fetch
请求,请使用 ses.fetch()。
¥This method will issue requests from the default session.
To send a fetch
request from another session, use ses.fetch().
有关更多详细信息,请参阅 fetch()
的 MDN 文档。
¥See the MDN documentation for
fetch()
for more
details.
限制:
¥Limitations:
-
net.fetch()
不支持data:
或blob:
方案。¥
net.fetch()
does not support thedata:
orblob:
schemes. -
integrity
选项的值被忽略。¥The value of the
integrity
option is ignored. -
返回的
Response
对象的.type
和.url
值不正确。¥The
.type
and.url
values of the returnedResponse
object are incorrect.
默认情况下,使用 net.fetch
发出的请求可以发送到 定制协议 以及 file:
,并且将触发 webRequest 处理程序(如果存在)。当在 RequestInit 中设置非标准 bypassCustomProtocolHandlers
选项时,将不会为此请求调用自定义协议处理程序。这允许将拦截的请求转发到内置处理程序。绕过自定义协议时,webRequest 处理程序仍将被触发。
¥By default, requests made with net.fetch
can be made to custom protocols
as well as file:
, and will trigger webRequest handlers if present.
When the non-standard bypassCustomProtocolHandlers
option is set in RequestInit,
custom protocol handlers will not be called for this request. This allows forwarding an
intercepted request to the built-in handler. webRequest
handlers will still be triggered when bypassing custom protocols.
protocol.handle('https', (req) => {
if (req.url === 'https://my-app.com') {
return new Response('<body>my app</body>')
} else {
return net.fetch(req, { bypassCustomProtocolHandlers: true })
}
})
注意:不支持 实用进程 自定义协议。
¥Note: in the utility process custom protocols are not supported.
net.isOnline()
返回 boolean
- 当前是否有互联网连接。
¥Returns boolean
- Whether there is currently internet connection.
返回值 false
是一个非常强烈的指示,表明用户将无法连接到远程站点。然而,返回值 true
是不确定的;即使某些链接已建立,也不确定对特定远程站点的特定连接尝试是否会成功。
¥A return value of false
is a pretty strong indicator that the user
won't be able to connect to remote sites. However, a return value of
true
is inconclusive; even if some link is up, it is uncertain
whether a particular connection attempt to a particular remote site
will be successful.
net.resolveHost(host, [options])
-
host
字符串 - 要解析的主机名。¥
host
string - Hostname to resolve.
返回 Promise<ResolvedHost>
- 使用 host
的已解析 IP 地址进行解析。
¥Returns Promise<ResolvedHost>
- Resolves with the resolved IP addresses for the host
.
此方法将从 默认会话 解析主机。要从另一个会话解析主机,请使用 ses.resolveHost()。
¥This method will resolve hosts from the default session. To resolve a host from another session, use ses.resolveHost().
属性
¥Properties
net.online
只读
¥net.online
Readonly
boolean
属性。当前是否有互联网连接。
¥A boolean
property. Whether there is currently internet connection.
返回值 false
是一个非常强烈的指示,表明用户将无法连接到远程站点。然而,返回值 true
是不确定的;即使某些链接已建立,也不确定对特定远程站点的特定连接尝试是否会成功。
¥A return value of false
is a pretty strong indicator that the user
won't be able to connect to remote sites. However, a return value of
true
is inconclusive; even if some link is up, it is uncertain
whether a particular connection attempt to a particular remote site
will be successful.