net
使用 Chromium 的本地网络库发出 HTTP/HTTPS 请求
net 模块是一个用于发起 HTTP(S) 请求的客户端 API。它类似于 Node.js 的 HTTP 和 HTTPS 模块,但使用 Chromium 的原生网络库,而不是 Node.js 的实现,从而提供对网络代理的更好支持。它还支持检查网络状态。
🌐 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 配置文件。
- HTTPS 请求的自动隧道。
- 支持使用基本、摘要、NTLM、Kerberos 或协商认证方案对代理进行身份验证。
- 支持流量监控代理:类似 Fiddler 的代理用于访问控制和监控。
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()
})
net API 只能在应用触发 ready 事件后使用。在 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 实例,这些 options 会直接转发给 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字符串 | 全局请求initRequestInit & { bypassCustomProtocolHandlers?: boolean }(可选)
返回 Promise<GlobalResponse> - 详情请参见 Response。
🌐 Returns Promise<GlobalResponse> - see Response.
发送请求,类似于渲染器中 fetch() 的工作方式,使用的是 Chrome 的网络栈。这与 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().
有关更多详情,请参阅 MDN 文档中的 fetch()。
🌐 See the MDN documentation for
fetch() for more
details.
限制:
🌐 Limitations:
net.fetch()不支持data:或blob:方案。integrity选项的值将被忽略。- 返回的
Response对象的.type和.url值不正确。
默认情况下,使用 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 })
}
})
在效用进程中,不支持自定义协议。
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字符串 - 要解析的主机名。
返回 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.