net
Выполнение HTTP/HTTPS запросов с использованием родной сетевой библиотеки Chromium
Модуль net представляет собой клиентский API для выдачи HTTP(S) запросов. Он похож на модули HTTP и HTTPS в Node.js, но использует собственную сетевую библиотеку Chromium вместо реализации Node.js, обеспечивая лучшую поддержку веб-прокси. It also supports checking network status.
Ниже приведен неполный список причин, по которым вы можете рассмотреть использование модуля net вместо собственных модулей Node.js:
- Автоматическое управление конфигурацией прокси системы, поддержка протокола wpad и файлов pac конфигурации прокси.
- Автоматическое туннелирование HTTPS запросов.
- Поддержка аутентификации прокси с помощью BASIC, DIGEST, NTLM, KERBEROS или NEGOTIATE схем аутентификации.
- Поддержка прокси-серверов для мониторинга трафика: 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()
})
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.
Методы
Модуль net имеет следующие методы:
net.request(options)
Returns ClientRequest
Creates a ClientRequest instance using the provided options which are directly forwarded to the ClientRequest constructor. Метод net.request будет использован для выполнения как безопасных, так и небезопасных HTTP-запросов в соответствии со схемой указанного протокола в объекте options.
net.fetch(input[, init])
inputstring | GlobalRequestinitRequestInit & { 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.
Пример:
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.
Ограничения:
net.fetch()does not support thedata:orblob:schemes.- The value of the
integrityoption is ignored. - The
.typeand.urlvalues of the returnedResponseobject 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 - 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.
net.resolveHost(host, [options])
hoststring - 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().
Свойства
net.online Readonly
A boolean property. 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.