Skip to main content

net

使用 Chromium 的本地网络库发出 HTTP/HTTPS 请求

进程:主进程工具进程

🌐 Process: Main, Utility

net 模块是一个用于发起 HTTP(S) 请求的客户端 API。它类似于 Node.js 的 HTTPHTTPS 模块,但使用 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)

返回 ClientRequest

🌐 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])

返回 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 })
}
})
note

效用进程中,不支持自定义协议。

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 字符串 - 要解析的主机名。
  • options 对象(可选)
    • queryType 字符串(可选)- 请求的 DNS 查询类型。如果未指定,解析器将根据 IPv4/IPv6 设置选择 A 或 AAAA(或两者):
      • A - 只获取 A 记录
      • AAAA - 仅获取 AAAA 记录。
    • source 字符串(可选)- 用于解析地址的来源。默认情况下,解析器会选择合适的来源。仅影响使用大型外部来源(例如调用系统进行解析或使用 DNS)。即使指定了来源,结果仍然可能来自缓存、解析“localhost”或 IP 字面值等。可取以下值之一:
      • any(默认)- 解析器将选择合适的来源。结果可能来自 DNS、多播 DNS、HOSTS 文件等
      • system - 结果将仅从系统或操作系统中检索,例如,通过 getaddrinfo() 系统调用
      • dns - 结果仅来自 DNS 查询
      • mdns - 结果仅来自多播 DNS 查询
      • localOnly - 不会使用外部来源。结果仅来自快速的本地来源,这些来源无论在何种源设置下都可用,例如缓存、主机文件、IP 字面量解析等。
    • cacheUsage 字符串(可选)- 指示可以用于提供响应的 DNS 缓存条目(如果有)。以下值之一:
      • allowed(默认)- 如果不是过时数据,结果可能来自主机缓存
      • staleAllowed - 即使已过期(由于失效或网络变化),结果也可能来自主机缓存
      • disallowed - 结果不会来自主机缓存。
    • secureDnsPolicy 字符串(可选)- 控制解析器在此请求中的安全 DNS 行为。取以下值之一:
      • allow(默认)
      • disable

返回 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.