Class: ClientRequest
Создает HTTP/HTTPS-запросы.
Process: Main, Utility
This class is not exported from the 'electron'
module. Он доступен только в качестве возвращаемого значения других методов в Electron API.
ClientRequest
реализует интерфейс Writable Stream и EventEmitter.
new ClientRequest(options)
options
(Object | string) - If options
is a string, it is interpreted as the request URL. Если это объект, ожидается полное указание HTTP запроса через следующие свойства:
method
string (опционально) - Метод HTTP-запроса. По умолчанию метод GET.
url
string (опционально) - URL запроса. Необходимо предоставить в абсолютной форме с протокольной схемой, указанной как http или https.
headers
Record<string, string | string[]> (optional) - Headers to be sent with the request.
session
Session (опционально) – экземпляр Session
, с которым ассоциирован данный запрос.
partition
string (опционально) – название раздела
, с которым ассоциирован данный запрос. По умолчанию является пустой строкой. The session
option supersedes partition
. Поэтому, если параметр session
явно указан, то partition
игнорируется.
credentials
string (optional) - Can be include
, omit
or same-origin
. Whether to send credentials with this request. If set to include
, credentials from the session associated with the request will be used. If set to omit
, credentials will not be sent with the request (and the 'login'
event will not be triggered in the event of a 401). If set to same-origin
, origin
must also be specified. This matches the behavior of the fetch option of the same name. If this option is not specified, authentication data from the session will be sent, and cookies will not be sent (unless useSessionCookies
is set).
useSessionCookies
boolean (optional) - Whether to send cookies with this request from the provided session. If credentials
is specified, this option has no effect. По умолчанию - false
.
protocol
string (опционально) - Может быть http:
или https:
. The protocol scheme in the form 'scheme:'. По умолчанию 'http:'.
host
string (опционально) - объединенное с номером порта доменное имя сервера 'доменное_имя:порт'.
hostname
string (опционально) – доменное имя сервера.
port
Integer (опционально) – номер порта сервера.
path
string (опционально) - часть пути запроса URL.
redirect
string (необязательный) - Позиция иконки, может иметь значения follow
, error
или manual
. The redirect mode for this request. When mode is error
, any redirection will be aborted. When mode is manual
the redirection will be cancelled unless request.followRedirect
is invoked synchronously during the redirect
event. По умолчанию - follow
.
origin
string (optional) - The origin URL of the request.
referrerPolicy
string (optional) - can be ""
, no-referrer
, no-referrer-when-downgrade
, origin
, origin-when-cross-origin
, unsafe-url
, same-origin
, strict-origin
, or strict-origin-when-cross-origin
. Значение по умолчанию: strict-origin-when-cross-origin
.
cache
string (optional) - can be default
, no-store
, reload
, no-cache
, force-cache
or only-if-cached
.
Свойства options
, такие как protocol
, host
, hostname
, port
и path
, строго следуют модели Node.js, которая описана в модуле URL.
Например, мы могли бы создать такой же запрос на 'github.com' следующим образом:
const request = net.request({
method: 'GET',
protocol: 'https:',
hostname: 'github.com',
port: 443,
path: '/'
})
События экземпляра
Событие: 'response'
Возвращает:
Событие: 'login'
Возвращает:
authInfo
Object
isProxy
boolean
scheme
string
host
string
port
Integer
realm
string
callback
Function
username
string (optional)
password
string (optional)
Происходит, когда прокси-сервер, выполняющий проверку подлинности, запрашивает учетные данные пользователя.
Ожидается, что функция callback
будет вызвана с учетными данными пользователя:
username
string
password
string
request.on('login', (authInfo, callback) => {
callback('username', 'password')
})
Предоставление пустых учетных данных отменит запрос и сообщит об ошибке проверки подлинности в объекте ответа:
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`)
response.on('error', (error) => {
console.log(`ERROR: ${JSON.stringify(error)}`)
})
})
request.on('login', (authInfo, callback) => {
callback()
})
Событие: 'finish'
Происходит сразу после того, как последняя часть данных запроса
была записана в объект request
.
Событие: 'abort'
Возникает при прерывании request
. Событие abort
не будет запущено, если request
уже закрыт.