类:ClientRequest
类:ClientRequest
🌐 Class: ClientRequest
发起 HTTP/HTTPS 请求。
进程:主进程,工具
此类未从 'electron' 模块导出。它仅作为 Electron API 中其他方法的返回值可用。
ClientRequest 实现了 Writable Stream 接口,因此它是一个 事件触发器。
new ClientRequest(options)
options 属性如 protocol、host、hostname、port 和 path 严格遵循 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:
responseIncomingMessage - 表示 HTTP 响应消息的对象。
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 事件表示在 request 或 response 对象上将不再发出任何事件。
🌐 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字符串responseHeadersRecord<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-LengthHostTrailer或TeUpgradeCookie2Keep-AliveTransfer-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 事件,中止操作将不会生效。否则,正在进行的事件将触发 abort 和 close 事件。此外,如果有正在进行的响应对象,它将触发 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,则current和total都将被设置为 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.