类: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
属性(例如 protocol
、host
、hostname
、port
和 path
)严格遵循 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:
-
response
IncomingMessage - 表示 HTTP 响应消息的对象。¥
response
IncomingMessage - An object representing the HTTP response message.
事件:'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
事件表示 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.
事件:'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
-
Trailer
或Te
¥
Trailer
orTe
-
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
事件,则中止操作将无效。否则,正在进行的事件将发出 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
布尔值 - 请求当前是否处于活动状态。如果为 false,则不会设置其他属性¥
active
boolean - Whether the request is currently active. If this is false no other properties will be set -
started
布尔值 - 是否开始上传。如果为 false,则current
和total
都将设置为 0。¥
started
boolean - Whether the upload has started. If this is false bothcurrent
andtotal
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.