net
Emitir solicitudes HTTP/HTTPS usando la biblioteca de red nativa de Chromium
El módulo net
es un lado del cliente API para tratar pedidos HTTP(S). Si es similar a los módulos HTTP y HTTPS de Node.js pero usa la biblioteca de la red nativa de Chromium en vez de las aplicaciones Node.js, ofreciendo un mejor soporte a los proxies de la web. It also supports checking network status.
La siguiente es una lista no completa de por qué debería considerar usar el módulo net
en vez de los módulos nativos Node.js:
- Gestión automática del sistema de configuración de proxy, soporte del protocolo wpad y el paquete de archivos de configuración del proxy.
- Túnel automático para peticiones HTTPS.
- Soportar los proxies de autentificación usando basic, digest, NTLM, Kerberos, o negociar esquemas de autentificación.
- Soporta proxies para monitoreo de tráfico: Fiddler como proxies usados para el acceso, el control y el monitoreo.
Los componentes API (incluyendo clases, métodos, propiedades y nombres de eventos) son similares a esos usados en Node.js.
Ejemplo de uso:
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()
})
La API net
puede ser utilizada solo después que la aplicación emita el evento ready
. Intentar usar el módulo antes del evento ready
lanzará un error.
Métodos
El módulo net
tiene los siguientes métodos:
net.request(options)
Devuelve ClientRequest
Crea una instancia ClientRequest
usando la options
proveída la cual son directamente reenviadas al constructor ClientRequest
. El método net.request
será usado para emitir solicitudes HTTP tanto seguras como inseguras dependiendo de lo especificado en el esquema de protocolo en el objeto options
.
net.fetch(input[, init])
input
string | GlobalRequestinit
RequestInit & { bypassCustomProtocolHandlers?: boolean } (optional)
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.
Ejemplo:
async function example () {
const response = await net.fetch('https://my.app')
if (response.ok) {
const body = await response.json()
// ... use the result.
}
}
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.
Limitaciones:
net.fetch()
does not support thedata:
orblob:
schemes.- The value of the
integrity
option is ignored. - The
.type
and.url
values of the returnedResponse
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()
Devuelve boolean
- Si actualmente hay conexión a internet.
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
string - Hostname to resolve.
Returns Promise<ResolvedHost> - Resolves with the resolved IP addresses for the host
.
This method will resolve hosts from the default session. To resolve a host from another session, use ses.resolveHost().
Propiedades
net.online
Readonly
Una propiedad boolean
. Whether there is currently internet connection.
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.