Skip to main content

类:ClientRequest

类:ClientRequest

🌐 Class: ClientRequest

发起 HTTP/HTTPS 请求。

进程:主进程工具
此类未从 'electron' 模块导出。它仅作为 Electron API 中其他方法的返回值可用。

ClientRequest 实现了 Writable Stream 接口,因此它是一个 事件触发器

new ClientRequest(options)

  • options(对象 | 字符串)- 如果 options 是字符串,则将其解释为请求的 URL。如果它是对象,则期望通过以下属性完整指定 HTTP 请求:
    • method 字符串(可选)- HTTP 请求方法。默认为 GET 方法。
    • url 字符串(可选)- 请求的 URL。必须以绝对形式提供,并且协议方案需指定为 http 或 https。
    • headers Record<string, string | string[]> (可选)- 随请求发送的头部。
    • session 会话(可选)- 与请求关联的 Session 实例。
    • partition 字符串(可选)- 与请求关联的 partition 的名称。默认值为空字符串。session 选项会覆盖 partition。因此,如果明确指定了 session,则会忽略 partition
    • bypassCustomProtocolHandlers 布尔值(可选)- 当设置为 true 时,已为请求的 URL 方案注册的自定义协议处理程序将不会被调用。这允许将被拦截的请求转发给内置处理程序。即使绕过自定义协议,webRequest 处理程序仍将被触发。默认值为 false
    • credentials 字符串(可选)- 可以是 includeomitsame-origin。是否在此请求中发送 凭据。如果设置为 include,则将使用与请求关联的会话中的凭据。如果设置为 omit,则不会随请求发送凭据(在发生 401 时也不会触发 'login' 事件)。如果设置为 same-origin,还必须指定 origin。这与同名的 fetch 选项的行为相匹配。如果未指定此选项,将会发送会话中的身份验证数据,但不会发送 cookie(除非设置了 useSessionCookies)。
    • useSessionCookies 布尔值(可选)- 是否从提供的会话发送此请求的 cookies。如果指定了 credentials,此选项将无效。默认值为 false
    • protocol 字符串(可选)- 可以是 http:https:。协议格式为 'scheme:'。默认值为 'http:'。
    • host 字符串(可选)- 服务器主机,由主机名和端口号拼接而成,格式为 'hostname:port'。
    • hostname 字符串(可选)- 服务器主机名。
    • port 整数(可选)- 服务器监听的端口号。
    • path 字符串(可选)- 请求 URL 的路径部分。
    • redirect 字符串(可选)- 可以是 followerrormanual。此请求的重定向模式。当模式为 error 时,任何重定向都会被中止。当模式为 manual 时,除非在 redirect 事件期间同步调用 request.followRedirect,否则重定向将被取消。默认值为 follow
    • origin 字符串(可选)- 请求的来源 URL。
    • referrerPolicy 字符串(可选)- 可以是 ""、no-referrerno-referrer-when-downgradeoriginorigin-when-cross-originunsafe-urlsame-originstrict-originstrict-origin-when-cross-origin。默认为 strict-origin-when-cross-origin
    • cache 字符串(可选) - 可以是 defaultno-storereloadno-cacheforce-cacheonly-if-cached
    • priority 字符串(可选)- 可以是 throttledidlelowestlowmediumhighest。默认值为 idle
    • priorityIncremental 布尔值(可选)——作为 HTTP 可扩展优先级(RFC 9218)的一部分的增量加载标志。默认值为 true

options 属性如 protocolhosthostnameportpath 严格遵循 Node.js 模型,如 URL 模块中所述。

例如,我们可以像下面这样向 'github.com' 创建相同的请求:

🌐 For instance, we could have created the same request to 'github.com' as follows:

const request = net.request({
method: 'GET',
protocol: 'https:',
hostname: 'github.com',
port: 443,
path: '/'
})

实例事件

🌐 Instance Events

Event: 'response'

返回:

🌐 Returns:

Event: 'login'

返回:

🌐 Returns:

  • authInfo 对象
    • isProxy 布尔值
    • scheme 字符串
    • host 字符串
    • port 整数
    • realm 字符串
  • callback 函数
    • username 字符串(可选)
    • password 字符串(可选)

当身份验证代理请求用户凭据时发出。

🌐 Emitted when an authenticating proxy is asking for user credentials.

callback 函数预计会使用用户凭据进行回调:

🌐 The callback function is expected to be called back with user credentials:

  • username 字符串
  • password 字符串
request.on('login', (authInfo, callback) => {
callback('username', 'password')
})

提供空凭证将取消请求,并在响应对象上报告身份验证错误:

🌐 Providing empty credentials will cancel the request and report an authentication error on the response object:

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

Event: 'finish'

request 的最后一块数据写入 request 对象之后立即发出。

🌐 Emitted just after the last chunk of the request's data has been written into the request object.

Event: 'abort'

request 被中止时触发。如果 request 已经关闭,则不会触发 abort 事件。

🌐 Emitted when the request is aborted. The abort event will not be fired if the request is already closed.

Event: 'error'

返回:

🌐 Returns:

  • error 错误 - 一个提供有关失败信息的错误对象。

net 模块无法发出网络请求时触发。通常当 request 对象触发 error 事件时,随后会触发 close 事件,并且不会提供响应对象。

🌐 Emitted when the net module fails to issue a network request. Typically when the request object emits an error event, a close event will subsequently follow and no response object will be provided.

Event: 'close'

作为 HTTP 请求-响应事务中最后一个事件发出。close 事件表示在 requestresponse 对象上将不再发出任何事件。

🌐 Emitted as the last event in the HTTP request-response transaction. The close event indicates that no more events will be emitted on either the request or response objects.

Event: 'redirect'

返回:

🌐 Returns:

  • statusCode 整数
  • method 字符串
  • redirectUrl 字符串
  • responseHeaders Record<string, string[]>

当服务器返回重定向响应时(例如 301 永久移动)会触发此事件。调用 request.followRedirect 将继续进行重定向。如果处理了此事件,则必须同步调用 request.followRedirect,否则请求将被取消。

🌐 Emitted when the server returns a redirect response (e.g. 301 Moved Permanently). Calling request.followRedirect will continue with the redirection. If this event is handled, request.followRedirect must be called synchronously, otherwise the request will be cancelled.

实例属性

🌐 Instance Properties

request.chunkedEncoding

boolean 用于指定请求是否使用 HTTP 分块传输编码。默认为 false。该属性是可读可写的,但只能在第一次写操作之前设置,因为此时 HTTP 头还未发送到网络上。在第一次写操作之后尝试设置 chunkedEncoding 属性将抛出错误。

🌐 A boolean specifying whether the request will use HTTP chunked transfer encoding or not. Defaults to false. The property is readable and writable, however it can be set only before the first write operation as the HTTP headers are not yet put on the wire. Trying to set the chunkedEncoding property after the first write will throw an error.

如果需要发送大请求体,强烈建议使用分块编码,因为数据将以小块流式传输,而不是在 Electron 进程内存中进行内部缓冲。

🌐 Using chunked encoding is strongly recommended if you need to send a large request body as data will be streamed in small chunks instead of being internally buffered inside Electron process memory.

实例方法

🌐 Instance Methods

request.setHeader(name, value)

  • name 字符串 - 额外的 HTTP 头名称。
  • value 字符串 - 额外的 HTTP 头部值。

添加一个额外的 HTTP 头。头名称将按原样使用,不会转换为小写。此方法只能在第一次写入之前调用。在第一次写入之后调用此方法将抛出错误。如果传入的值不是 string,将调用其 toString() 方法以获取最终值。

🌐 Adds an extra HTTP header. The header name will be issued as-is without lowercasing. It can be called only before first write. Calling this method after the first write will throw an error. If the passed value is not a string, its toString() method will be called to obtain the final value.

某些头部不能由应用设置。这些头部列在下面。有关受限头部的更多信息,请参阅Chromium 的头部工具

🌐 Certain headers are restricted from being set by apps. These headers are listed below. More information on restricted headers can be found in Chromium's header utils.

  • Content-Length
  • Host
  • TrailerTe
  • Upgrade
  • Cookie2
  • Keep-Alive
  • Transfer-Encoding

此外,将 Connection 头设置为 upgrade 的值也是不允许的。

🌐 Additionally, setting the Connection header to the value upgrade is also disallowed.

request.getHeader(name)

  • name 字符串 - 指定一个额外的头名称。

返回 string - 之前设置的额外头名称的值。

🌐 Returns string - The value of a previously set extra header name.

request.removeHeader(name)

  • name 字符串 - 指定一个额外的头名称。

移除先前设置的额外头部名称。此方法只能在第一次写入之前调用。在第一次写入之后尝试调用将抛出错误。

🌐 Removes a previously set extra header name. This method can be called only before first write. Trying to call it after the first write will throw an error.

request.write(chunk[, encoding][, callback])

  • chunk(字符串 | 缓冲区)- 请求主体数据的一部分。如果它是字符串,则使用指定的编码将其转换为缓冲区。
  • encoding 字符串(可选)- 用于将字符串块转换为 Buffer 对象。默认值为 'utf-8'。
  • callback 函数(可选)- 在写操作结束后调用。

callback 本质上是一个虚拟函数,其引入目的是为了保持与 Node.js API 的相似性。在 chunk 内容被传递到 Chromium 网络层之后的下一个 tick 中,它会被异步调用。与 Node.js 的实现不同,不保证在调用 callback 之前 chunk 内容已经被刷新到网络上。

向请求主体添加一块数据。第一次写入操作可能会导致请求头被发送。第一次写入操作之后,不允许添加或移除自定义头。

🌐 Adds a chunk of data to the request body. The first write operation may cause the request headers to be issued on the wire. After the first write operation, it is not allowed to add or remove a custom header.

request.end([chunk][, encoding][, callback])

  • chunk(字符串 | 缓冲区)(可选)
  • encoding 字符串(可选)
  • callback 功能(可选)

返回 this

🌐 Returns this.

发送请求数据的最后一块。随后将不允许进行写入或结束操作。finish 事件会在结束操作之后立即触发。

🌐 Sends the last chunk of the request data. Subsequent write or end operations will not be allowed. The finish event is emitted just after the end operation.

request.abort()

取消正在进行的 HTTP 事务。如果请求已经触发 close 事件,中止操作将不会生效。否则,正在进行的事件将触发 abortclose 事件。此外,如果有正在进行的响应对象,它将触发 aborted 事件。

🌐 Cancels an ongoing HTTP transaction. If the request has already emitted the close event, the abort operation will have no effect. Otherwise an ongoing event will emit abort and close events. Additionally, if there is an ongoing response object, it will emit the aborted event.

request.followRedirect()

继续任何待处理的重定向。只能在 'redirect' 事件期间调用。

🌐 Continues any pending redirection. Can only be called during a 'redirect' event.

request.getUploadProgress()

返回 Object

🌐 Returns Object:

  • active 布尔值 - 请求当前是否处于激活状态。如果为假,则不会设置其他属性
  • started 布尔值 - 上传是否已开始。如果为 false,则 currenttotal 都将被设置为 0。
  • current 整数 - 目前已上传的字节数
  • total 整数 - 本次请求将上传的字节数

你可以将此方法与 POST 请求结合使用,以获取文件上传或其他数据传输的进度。

🌐 You can use this method in conjunction with POST requests to get the progress of a file upload or other data transfer.