Skip to main content

类:ClientRequest

类:ClientRequest

¥Class: ClientRequest

发出 HTTP/HTTPS 请求。

¥Make HTTP/HTTPS requests.

进程:主进程, 实用工具
该类不是从 'electron' 模块导出的。它仅可用作 Electron API 中其他方法的返回值。

¥Process: Main, Utility
This class is not exported from the 'electron' module. It is only available as a return value of other methods in the Electron API.

ClientRequest 实现了 可写流 接口,因此是 EventEmitter

¥ClientRequest implements the Writable Stream interface and is therefore an EventEmitter.

new ClientRequest(options)

  • options(Object | string) - 如果 options 是字符串,则将其解释为请求 URL。如果它是一个对象,则期望通过以下属性完全指定 HTTP 请求:

    ¥options (Object | string) - If options is a string, it is interpreted as the request URL. If it is an object, it is expected to fully specify an HTTP request via the following properties:

    • method 字符串(可选) - HTTP 请求方法。默认为 GET 方法。

      ¥method string (optional) - The HTTP request method. Defaults to the GET method.

    • url 字符串(可选) - 请求网址。必须以绝对形式提供,协议方案指定为 http 或 https。

      ¥url string (optional) - The request URL. Must be provided in the absolute form with the protocol scheme specified as http or https.

    • headers Record<string,字符串 | string[]>(可选) - 随请求一起发送的标头。

      ¥headers Record<string, string | string[]> (optional) - Headers to be sent with the request.

    • session 会议(可选) - 与请求关联的 Session 实例。

      ¥session Session (optional) - The Session instance with which the request is associated.

    • partition 字符串(可选) - 与请求关联的 partition 的名称。默认为空字符串。session 选项取代 partition。因此,如果显式指定 session,则忽略 partition

      ¥partition string (optional) - The name of the partition with which the request is associated. Defaults to the empty string. The session option supersedes partition. Thus if a session is explicitly specified, partition is ignored.

    • credentials 字符串(可选) - 可以是 includeomitsame-origin。是否随此请求一起发送 credentials。如果设置为 include,将使用与请求关联的会话中的凭据。如果设置为 omit,凭证将不会随请求一起发送(并且在 401 事件中不会触发 'login' 事件)。如果设置为 same-origin,则还必须指定 origin。这与同名的 fetch 选项的行为相匹配。如果未指定此选项,将发送会话中的身份验证数据,并且不会发送 cookie(除非设置了 useSessionCookies)。

      ¥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 布尔值(可选) - 是否从所提供的会话中随此请求发送 cookie。如果指定了 credentials,则该选项无效。默认为 false

      ¥useSessionCookies boolean (optional) - Whether to send cookies with this request from the provided session. If credentials is specified, this option has no effect. Default is false.

    • protocol 字符串(可选) - 可以是 http:https:。协议方案采用 '方案:' 形式。默认为 'http:'。

      ¥protocol string (optional) - Can be http: or https:. The protocol scheme in the form 'scheme:'. Defaults to 'http:'.

    • host 字符串(可选) - 服务器主机以主机名和端口号 'hostname:port' 的串联形式提供。

      ¥host string (optional) - The server host provided as a concatenation of the hostname and the port number 'hostname:port'.

    • hostname 字符串(可选) - 服务器主机名。

      ¥hostname string (optional) - The server host name.

    • port 整数(可选) - 服务器的监听端口号。

      ¥port Integer (optional) - The server's listening port number.

    • path 字符串(可选) - 请求 URL 的路径部分。

      ¥path string (optional) - The path part of the request URL.

    • redirect 字符串(可选) - 可以是 followerrormanual。此请求的重定向模式。当模式为 error 时,任何重定向都将被中止。当模式为 manual 时,除非在 redirect 事件期间同步调用 request.followRedirect,否则重定向将被取消。默认为 follow

      ¥redirect string (optional) - Can be follow, error or 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. Defaults to follow.

    • origin 字符串(可选) - 请求的原始 URL。

      ¥origin string (optional) - The origin URL of the request.

    • referrerPolicy 字符串(可选) - 可以是 ""no-referrerno-referrer-when-downgradeoriginorigin-when-cross-originunsafe-urlsame-originstrict-originstrict-origin-when-cross-origin。默认为 strict-origin-when-cross-origin

      ¥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. Defaults to strict-origin-when-cross-origin.

    • cache 字符串(可选) - 可以是 defaultno-storereloadno-cacheforce-cacheonly-if-cached

      ¥cache string (optional) - can be default, no-store, reload, no-cache, force-cache or only-if-cached.

options 属性(例如 protocolhosthostnameportpath)严格遵循 URL 模块中描述的 Node.js 模型。

¥options properties such as protocol, host, hostname, port and path strictly follow the Node.js model as described in the URL module.

例如,我们可以向 '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

事件:'response'

¥Event: 'response'

返回:

¥Returns:

事件:'login'

¥Event: 'login'

返回:

¥Returns:

  • authInfo 对象

    ¥authInfo Object

    • isProxy 布尔值

      ¥isProxy boolean

    • scheme 字符串

      ¥scheme string

    • host 字符串

      ¥host string

    • port 整数

      ¥port Integer

    • realm 字符串

      ¥realm string

  • callback 函数

    ¥callback Function

    • username 字符串(可选)

      ¥username string (optional)

    • password 字符串(可选)

      ¥password string (optional)

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

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

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

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

  • username 字符串

    ¥username string

  • password 字符串

    ¥password string

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

事件:'finish'

¥Event: 'finish'

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

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

事件:'abort'

¥Event: 'abort'

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

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

事件:'error'

¥Event: 'error'

返回:

¥Returns:

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

    ¥error Error - an error object providing some information about the failure.

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.

事件:'close'

¥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.

事件:'redirect'

¥Event: 'redirect'

返回:

¥Returns:

  • statusCode 整数

    ¥statusCode Integer

  • method 字符串

    ¥method string

  • redirectUrl 字符串

    ¥redirectUrl string

  • responseHeaders 记录<字符串,字符串[]>

    ¥responseHeaders Record<string, string[]>

当服务器返回重定向响应(例如 301 Moved Permanently)时发出。调用 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 标头名称。

    ¥name string - An extra HTTP header name.

  • value 字符串 - 额外的 HTTP 标头值。

    ¥value string - An extra HTTP header value.

添加额外的 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

    ¥Trailer or Te

  • Upgrade

  • Cookie2

  • Keep-Alive

  • Transfer-Encoding

此外,也不允许将 Connection 标头设置为值 upgrade

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

request.getHeader(name)

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

    ¥name string - Specify an extra header name.

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

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

request.removeHeader(name)

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

    ¥name string - Specify an extra header 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(string | Buffer) - 请求正文的数据块。如果是字符串,则使用指定的编码将其转换为 Buffer。

    ¥chunk (string | Buffer) - A chunk of the request body's data. If it is a string, it is converted into a Buffer using the specified encoding.

  • encoding 字符串(可选) - 用于将字符串块转换为 Buffer 对象。默认为 'utf-8'。

    ¥encoding string (optional) - Used to convert string chunks into Buffer objects. Defaults to 'utf-8'.

  • callback 功能(可选) - 写操作结束后调用。

    ¥callback Function (optional) - Called after the write operation ends.

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

¥callback is essentially a dummy function introduced in the purpose of keeping similarity with the Node.js API. It is called asynchronously in the next tick after chunk content have been delivered to the Chromium networking layer. Contrary to the Node.js implementation, it is not guaranteed that chunk content have been flushed on the wire before callback is called.

将一大块数据添加到请求正文。第一个写入操作可能会导致请求标头在线上发出。第一次写入操作后,不允许添加或删除自定义标头。

¥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(字符串 | 缓冲区)(可选)

    ¥chunk (string | Buffer) (optional)

  • encoding 字符串(可选)

    ¥encoding string (optional)

  • callback 功能(可选)

    ¥callback Function (optional)

返回 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 布尔值 - 请求当前是否处于活动状态。如果为 false,则不会设置其他属性

    ¥active boolean - Whether the request is currently active. If this is false no other properties will be set

  • started 布尔值 - 是否开始上传。如果为 false,则 currenttotal 都将设置为 0。

    ¥started boolean - Whether the upload has started. If this is false both current and total will be set to 0.

  • current 整数 - 到目前为止已上传的字节数

    ¥current Integer - The number of bytes that have been uploaded so far

  • total 整数 - 此请求将上传的字节数

    ¥total Integer - The number of bytes that will be uploaded this request

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

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