Skip to main content

net

使用 Chromium 的原生网络库发出 HTTP/HTTPS 请求

¥Issue HTTP/HTTPS requests using Chromium's native networking library

进程:主进程实用工具

¥Process: Main, Utility

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

返回 ClientRequest

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

返回 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 the data: or blob: schemes.

  • integrity 选项的值被忽略。

    ¥The value of the integrity option is ignored.

  • 返回的 Response 对象的 .type.url 值不正确。

    ¥The .type and .url values of the returned Response 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.

  • options 对象(可选)

    ¥options Object (optional)

    • queryType 字符串(可选) - 请求的 DNS 查询类型。如果未指定,解析器将根据 IPv4/IPv6 设置选择 A 或 AAAA(或两者):

      ¥queryType string (optional) - Requested DNS query type. If unspecified, resolver will pick A or AAAA (or both) based on IPv4/IPv6 settings:

      • A - 只获取 A 记录

        ¥A - Fetch only A records

      • AAAA - 仅获取 AAAA 记录。

        ¥AAAA - Fetch only AAAA records.

    • source 字符串(可选) - 用于解析地址的源。默认值允许解析器选择合适的源。仅影响大型外部资源的使用(例如调用系统进行解析或使用 DNS)。即使指定了源,结果仍然可以来自缓存、解析 "localhost" 或 IP 字面量等。以下值之一:

      ¥source string (optional) - The source to use for resolved addresses. Default allows the resolver to pick an appropriate source. Only affects use of big external sources (e.g. calling the system for resolution or using DNS). Even if a source is specified, results can still come from cache, resolving "localhost" or IP literals, etc. One of the following values:

      • any(默认) - 解析器将选择合适的源。结果可能来自 DNS、MulticastDNS、HOSTS 文件等

        ¥any (default) - Resolver will pick an appropriate source. Results could come from DNS, MulticastDNS, HOSTS file, etc

      • system - 结果只能从系统或操作系统中检索,例如 通过 getaddrinfo() 系统调用

        ¥system - Results will only be retrieved from the system or OS, e.g. via the getaddrinfo() system call

      • dns - 结果仅来自 DNS 查询

        ¥dns - Results will only come from DNS queries

      • mdns - 结果仅来自多播 DNS 查询

        ¥mdns - Results will only come from Multicast DNS queries

      • localOnly - 不会使用任何外部资源。结果仅来自快速本地源,无论源设置如何,例如 缓存、hosts 文件、IP 字面量解析等

        ¥localOnly - No external sources will be used. Results will only come from fast local sources that are available no matter the source setting, e.g. cache, hosts file, IP literal resolution, etc.

    • cacheUsage 字符串(可选) - 指示哪些 DNS 缓存条目(如果有)可用于提供响应。以下值之一:

      ¥cacheUsage string (optional) - Indicates what DNS cache entries, if any, can be used to provide a response. One of the following values:

      • allowed(默认) - 如果结果未过时,则可能来自主机缓存

        ¥allowed (default) - Results may come from the host cache if non-stale

      • staleAllowed - 即使结果已过时(由于过期或网络更改),也可能来自主机缓存

        ¥staleAllowed - Results may come from the host cache even if stale (by expiration or network changes)

      • disallowed - 结果不会来自主机缓存。

        ¥disallowed - Results will not come from the host cache.

    • secureDnsPolicy 字符串(可选) - 控制解析器对此请求的安全 DNS 行为。以下值之一:

      ¥secureDnsPolicy string (optional) - Controls the resolver's Secure DNS behavior for this request. One of the following values:

      • allow(默认)

        ¥allow (default)

      • 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.