跳转到主内容

net

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

Process: Main, Utility

net 模块是一个发送 HTTP(S) 请求的客户端API。 它类似于Node.js的HTTPHTTPS 模块 ,但它使用的是Chromium原生网络库来替代Node.js的实现,提供更好的网络代理支持。 它还支持检查网络状态。

下面是一个非详尽的列表, 用于说明为什么使用 net 模块而不是原生Node. js 模块:

  • 系统代理配置的自动管理, 支持 wpad 协议和代理 pac 配置文件。
  • HTTPS 请求的自动隧道。
  • 支持使用basic、digest、NTLM、Kerberos 或协商身份验证方案对代理进行身份验证。
  • 支持传输监控代理: 类似于Fiddler代理,用于访问控制和监视。

这些 API 组件 (包括类、方法、属性和事件名称) 都很像 Node.js。

示例:

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 事件之前使用将引发 error。

方法

net 模块具有以下方法:

net.request(options)

返回 ClientRequest

使用 options 创建 ClientRequest 实例, 这些选项直接转发到 ClientRequest 的构造函数。 net.request 方法将根据 options 对象中的指定协议方案, 去发送安全和不安全的 HTTP 请求( both secure and insecure HTTP requests)。

net.fetch(input[, init])

Returns Promise<GlobalResponse> - see Response.

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.

示例:

async function example () {
const response = await net.fetch('https://my.app')
if (response.ok) {
const body = await response.json()
// ... use the result.
}
}

此方法将从default session发出请求。 如果想使用其他session发送 fetch 请求, 请使用ses.fetch().

See the MDN documentation for fetch() for more details.

局限性:

  • net.fetch() does not support the data: or blob: schemes.
  • The value of the integrity option is ignored.
  • The .type and .url values of the returned Response object are incorrect.

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()

Returns boolean - 当前是否联网

返回 false 意味着很大概率下当前用户无法连接远程网站。 然而, 即使返回为 true 也无法保证一定可以连接到远程站点

net.resolveHost(host, [options])

  • host string - Hostname to resolve.
  • options Object (可选)
    • queryType string (optional) - Requested DNS query type. If unspecified, resolver will pick A or AAAA (or both) based on IPv4/IPv6 settings:
      • A - Fetch only A records
      • AAAA - Fetch only AAAA records.
    • 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. 以下值之一:
      • any (default) - Resolver will pick an appropriate source. Results could come from DNS, MulticastDNS, HOSTS file, etc
      • system - Results will only be retrieved from the system or OS, e.g. via the getaddrinfo() system call
      • dns - Results will only come from DNS queries
      • mdns - Results will only come from Multicast DNS queries
      • 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 string (optional) - Indicates what DNS cache entries, if any, can be used to provide a response. 以下值之一:
      • allowed (default) - Results may come from the host cache if non-stale
      • staleAllowed - Results may come from the host cache even if stale (by expiration or network changes)
      • disallowed - Results will not come from the host cache.
    • secureDnsPolicy string (optional) - Controls the resolver's Secure DNS behavior for this request. 以下值之一:
      • allow (default)
      • disable

Returns Promise<ResolvedHost> - Resolves with the resolved IP addresses for the host.

此方法将从default session中解析主机。 若要从另一个会话中解析主机,请使用ses.resolveHost()

属性

net.online 只读

boolean 属性。 目前是否有互联网连接。

返回 false 意味着很大概率下当前用户无法连接远程网站。 然而, 即使返回为 true 也无法保证一定可以连接到远程站点