跳转到主要内容

类:ClientRequest

类:ClientRequest

进行 HTTP/HTTPS 请求。

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

ClientRequest 实现 Writable Stream 接口,因此它是一个 EventEmitter

new ClientRequest(options)

  • options (Object | string) - 如果 options 是一个字符串,它将被解释为请求 URL。如果它是一个对象,它应该通过以下属性完全指定一个 HTTP 请求
    • method string (可选) - HTTP 请求方法。默认为 GET 方法。
    • url string (可选) - 请求 URL。必须以绝对形式提供,并且协议方案指定为 http 或 https。
    • headers Record<string, string | string[]> (可选) - 要随请求一起发送的标头。
    • session Session (可选) - 与请求关联的 Session 实例。
    • partition string (可选) - 与请求关联的 partition 的名称。默认为空字符串。session 选项会覆盖 partition。因此,如果显式指定了 session,则会忽略 partition
    • credentials string (可选) - 可以是 includeomitsame-origin。是否将 凭据与此请求一起发送。如果设置为 include,将使用与请求关联的会话中的凭据。如果设置为 omit,则不会将凭据与请求一起发送(并且在 401 的情况下不会触发 'login' 事件)。如果设置为 same-origin,则还必须指定 origin。这与同名 fetch 选项的行为相匹配。如果未指定此选项,则会发送会话中的身份验证数据,并且不会发送 cookie(除非设置了 useSessionCookies)。
    • useSessionCookies boolean (可选) - 是否将提供的会话中的 cookie 与此请求一起发送。如果指定了 credentials,则此选项无效。默认为 false
    • protocol string (可选) - 可以是 http:https:。协议方案的形式为“scheme:”。默认为 'http:'。
    • host string (可选) - 服务器主机,提供为主机名和端口号的串联“hostname:port'.
    • hostname string (可选) - 服务器主机名。
    • port Integer (可选) - 服务器的监听端口号。
    • path string (可选) - 请求 URL 的路径部分。
    • redirect string (可选) - 可以是 followerrormanual。此请求的重定向模式。当模式为 error 时,任何重定向都将被中止。当模式为 manual 时,除非在 redirect 事件期间同步调用 request.followRedirect,否则重定向将被取消。默认为 follow
    • origin string (可选) - 请求的源 URL。
    • referrerPolicy string (可选) - 可以是 ""、no-referrerno-referrer-when-downgradeoriginorigin-when-cross-originunsafe-urlsame-originstrict-originstrict-origin-when-cross-origin。默认为 strict-origin-when-cross-origin
    • cache string (可选) - 可以是 defaultno-storereloadno-cacheforce-cacheonly-if-cached
    • priority string (可选) - 可以是 throttledidlelowestlowmediumhighest。默认为 idle
    • priorityIncremental boolean (可选) - 作为 HTTP 可扩展优先级 (RFC 9218) 的一部分的增量加载标志。默认为 true

options 的属性,例如 protocolhosthostnameportpath,严格遵循 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 (可选)
    • password string (可选)

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

预计 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 的数据最后一块被写入 request 对象后立即发出。

事件:'abort'

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

事件:‘error’

返回

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

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

事件:'close'

作为 HTTP 请求-响应事务的最后一个事件发出。close 事件表示 requestresponse 对象上都不会再发出事件。

事件:'redirect'

返回

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

当服务器返回重定向响应时(例如 301 Moved Permanently)发出。调用 request.followRedirect 将继续重定向。如果处理了此事件,则必须 **同步** 调用 request.followRedirect,否则请求将被取消。

实例属性

request.chunkedEncoding

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

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

实例方法

request.setHeader(name, value)

  • name string - 额外的 HTTP 标头名称。
  • value string - 额外的 HTTP 标头值。

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

应用程序无法设置某些标头。这些标头如下所列。有关受限标头的更多信息,请参阅 Chromium 的标头实用工具

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

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

request.getHeader(name)

  • name string - 指定额外的标头名称。

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

request.removeHeader(name)

  • name string - 指定额外的标头名称。

删除以前设置的额外标头名称。此方法只能在第一次写入之前调用。尝试在第一次写入后调用它将引发错误。

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

  • chunk (string | Buffer) - 请求正文数据的块。如果它是字符串,则使用指定的编码将其转换为 Buffer。
  • encoding string (可选) - 用于将字符串块转换为 Buffer 对象。默认为 'utf-8'。
  • callback Function (可选) - 写入操作完成后调用。

callback essentially is 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.(callback 基本上是一个占位符函数,引入该函数的目的是保持与 Node.js API 的相似性。它在 chunk 内容被传递到 Chromium 网络层后的下一个 tick 中异步调用。与 Node.js 实现相反,不能保证在调用 callback 之前 chunk 内容已经刷新到网络。)

向请求正文添加数据块。第一次写入操作可能会导致请求标头被发送到网络。第一次写入操作后,不允许添加或删除自定义标头。

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

  • chunk (string | Buffer) (可选)
  • encoding string (可选)
  • callback Function (可选)

返回 this

发送请求数据的最后一个块。不允许后续的写入或结束操作。end 操作完成后立即发出 finish 事件。

request.abort()

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

request.followRedirect()

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

request.getUploadProgress()

返回 Object

  • active boolean - 请求当前是否处于活动状态。如果为 false,则其他属性将不会被设置
  • started boolean - 上传是否已开始。如果为 false,则 currenttotal 都将设置为 0。
  • current Integer - 到目前为止已上传的字节数
  • total Integer - 此请求将上传的总字节数

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