net

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

进程:主进程

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

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

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

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

示例:

  1. const { app } = require('electron')
  2. app.whenReady().then(() => {
  3. const { net } = require('electron')
  4. const request = net.request('https://github.com')
  5. request.on('response', (response) => {
  6. console.log(`STATUS: ${response.statusCode}`)
  7. console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
  8. response.on('data', (chunk) => {
  9. console.log(`BODY: ${chunk}`)
  10. })
  11. response.on('end', () => {
  12. console.log('No more data in response.')
  13. })
  14. })
  15. request.end()
  16. })

只有在应用程序发出 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.

示例:

  1. async function example () {
  2. const response = await net.fetch('https://my.app')
  3. if (response.ok) {
  4. const body = await response.json()
  5. // ... use the result.
  6. }
  7. }

This method will issue requests from the default session. To send a fetch request from another session, use 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.

  1. protocol.handle('https', (req) => {
  2. if (req.url === 'https://my-app.com') {
  3. return new Response('<body>my app</body>')
  4. } else {
  5. return net.fetch(req, { bypassCustomProtocolHandlers: true })
  6. }
  7. })

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 也无法保证一定可以连接到远程站点