http.request(url[, options][, callback])


  • url <string> | <URL>

  • options <Object>

    • agent <http.Agent> | <boolean> 控制 Agent 的行为。可能的值:

      ¥agent <http.Agent> | <boolean> Controls Agent behavior. Possible values:

      • undefined(默认):使用 http.globalAgent 作为主机和端口。

        ¥undefined (default): use http.globalAgent for this host and port.

      • Agent 对象:显式使用传入的 Agent

        ¥Agent object: explicitly use the passed in Agent.

      • false:使用具有默认值的新 Agent

        ¥false: causes a new Agent with default values to be used.

    • auth <string> 用于计算授权标头的基本身份验证 ('user:password')。

      ¥auth <string> Basic authentication ('user:password') to compute an Authorization header.

    • createConnection <Function> 当不使用 agent 选项时,生成用于请求的套接字/流的函数。这可用于避免创建自定义 Agent 类只是为了覆盖默认的 createConnection 函数。有关详细信息,请参阅 agent.createConnection()。任何 Duplex 流都是有效的返回值。

      ¥createConnection <Function> A function that produces a socket/stream to use for the request when the agent option is not used. This can be used to avoid creating a custom Agent class just to override the default createConnection function. See agent.createConnection() for more details. Any Duplex stream is a valid return value.

    • defaultPort <number> 协议的默认端口。默认值:如果使用 Agent,则为 agent.defaultPort,否则为 undefined

      ¥defaultPort <number> Default port for the protocol. Default: agent.defaultPort if an Agent is used, else undefined.

    • family <number> 解析 hosthostname 时使用的 IP 地址族。有效值为 46。当未指定时,则将使用 IP v4 和 v6。

      ¥family <number> IP address family to use when resolving host or hostname. Valid values are 4 or 6. When unspecified, both IP v4 and v6 will be used.

    • headers <Object> 包含请求头的对象。

      ¥headers <Object> An object containing request headers.

    • hints <number> 可选 dns.lookup() 提示

      ¥hints <number> Optional dns.lookup() hints.

    • host <string> 要向其触发请求的服务器的域名或 IP 地址。默认值:'localhost'

      ¥host <string> A domain name or IP address of the server to issue the request to. Default: 'localhost'.

    • hostname <string> host 的别名。为了支持 url.parse(),如果同时指定了 hosthostname,则将使用 hostname

      ¥hostname <string> Alias for host. To support url.parse(), hostname will be used if both host and hostname are specified.

    • insecureHTTPParser <boolean> 使用不安全的 HTTP 解析器,当为 true 时接受无效的 HTTP 标头。应避免使用不安全的解析器。有关详细信息,请参阅 --insecure-http-parser。默认值:false

      ¥insecureHTTPParser <boolean> Use an insecure HTTP parser that accepts invalid HTTP headers when true. Using the insecure parser should be avoided. See --insecure-http-parser for more information. Default: false

    • joinDuplicateHeaders <boolean> 它使用 , 连接请求中多个标头的字段行值,而不是丢弃重复项。有关详细信息,请参阅 message.headers。默认值:false

      ¥joinDuplicateHeaders <boolean> It joins the field line values of multiple headers in a request with , instead of discarding the duplicates. See message.headers for more information. Default: false.

    • localAddress <string> 用于绑定网络连接的本地接口。

      ¥localAddress <string> Local interface to bind for network connections.

    • localPort <number> 连接的本地端口。

      ¥localPort <number> Local port to connect from.

    • lookup <Function> 自定义查找函数。默认值:dns.lookup()

      ¥lookup <Function> Custom lookup function. Default: dns.lookup().

    • maxHeaderSize <number> 对于从服务器接收到的响应,可选择覆盖 --max-http-header-size 的值(响应标头的最大长度,以字节为单位)。默认值:16384 (16 KiB)。

      ¥maxHeaderSize <number> Optionally overrides the value of --max-http-header-size (the maximum length of response headers in bytes) for responses received from the server. Default: 16384 (16 KiB).

    • method <string> 指定 HTTP 请求方法的字符串。默认值:'GET'

      ¥method <string> A string specifying the HTTP request method. Default: 'GET'.

    • path <string> 请求的路径。应包括查询字符串(如果有)。E.G.'/index.html?page=12'。当请求路径包含非法字符时抛出异常。目前,只有空格被拒绝,但将来可能会改变。默认值:'/'

      ¥path <string> Request path. Should include query string if any. E.G. '/index.html?page=12'. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. Default: '/'.

    • port <number> 远程服务器的端口。默认值:如果设置则为 defaultPort,否则为 80

      ¥port <number> Port of remote server. Default: defaultPort if set, else 80.

    • protocol <string> 要使用的协议。默认值:'http:'

      ¥protocol <string> Protocol to use. Default: 'http:'.

    • setHost <boolean> :指定是否自动添加 Host 标头。默认为 true

      ¥setHost <boolean>: Specifies whether or not to automatically add the Host header. Defaults to true.

    • signal <AbortSignal> :可用于中止正在进行的请求的中止信号。

      ¥signal <AbortSignal>: An AbortSignal that may be used to abort an ongoing request.

    • socketPath <string> Unix 域套接字。如果指定了 hostport 之一,则不能使用,因为它们指定了 TCP 套接字。

      ¥socketPath <string> Unix domain socket. Cannot be used if one of host or port is specified, as those specify a TCP Socket.

    • timeout <number> :以毫秒为单位指定套接字超时的数字。这将在连接套接字之前设置超时。

      ¥timeout <number>: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.

    • uniqueHeaders <Array> 只应发送一次的请求标头列表。如果标头的值是数组,则子项将使用 ; 连接。

      ¥uniqueHeaders <Array> A list of request headers that should be sent only once. If the header's value is an array, the items will be joined using ; .

  • callback <Function>

  • 返回:<http.ClientRequest>

    ¥Returns: <http.ClientRequest>

socket.connect() 中的 options 也受支持。

¥options in socket.connect() are also supported.

Node.js 为每个服务器维护多个连接以触发 HTTP 请求。此函数允许显式地触发请求。

¥Node.js maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.

url 可以是字符串或 URL 对象。如果 url 是字符串,则会自动使用 new URL() 解析。如果是 URL 对象,则会自动转换为普通的 options 对象。

¥url can be a string or a URL object. If url is a string, it is automatically parsed with new URL(). If it is a URL object, it will be automatically converted to an ordinary options object.

如果同时指定了 urloptions,则合并对象,options 属性优先。

¥If both url and options are specified, the objects are merged, with the options properties taking precedence.

可选的 callback 参数将被添加为 'response' 事件的单次监听器。

¥The optional callback parameter will be added as a one-time listener for the 'response' event.

http.request() 返回 http.ClientRequest 类的实例。ClientRequest 实例是可写流。如果需要使用 POST 请求上传文件,则写入 ClientRequest 对象。

¥http.request() returns an instance of the http.ClientRequest class. The ClientRequest instance is a writable stream. If one needs to upload a file with a POST request, then write to the ClientRequest object.

import http from 'node:http';
import { Buffer } from 'node:buffer';

const postData = JSON.stringify({
  'msg': 'Hello World!',
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(postData),
  },
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(postData);
req.end();const http = require('node:http');

const postData = JSON.stringify({
  'msg': 'Hello World!',
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(postData),
  },
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(postData);
req.end();

在示例中,调用了 req.end()。对于 http.request(),必须始终调用 req.end() 以表示请求结束 - 即使没有数据写入请求正文。

¥In the example req.end() was called. With http.request() one must always call req.end() to signify the end of the request - even if there is no data being written to the request body.

如果在请求期间遇到任何错误(无论是 DNS 解析、TCP 级别错误还是实际的 HTTP 解析错误),都会在返回的请求对象上触发 'error' 事件。与所有 'error' 事件一样,如果没有注册监听器,则会抛出错误。

¥If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object. As with all 'error' events, if no listeners are registered the error will be thrown.

有一些特殊的标头需要注意。

¥There are a few special headers that should be noted.

  • 发送“连接:keep-alive' 将通知 Node.js 与服务器的连接应该保持到下一个请求。

    ¥Sending a 'Connection: keep-alive' will notify Node.js that the connection to the server should be persisted until the next request.

  • 发送 '内容长度' 标头将禁用默认的分块编码。

    ¥Sending a 'Content-Length' header will disable the default chunked encoding.

  • 发送 '预计' 标头将立即发送请求标头。通常,发送 'Expect:100-continue',应设置 'continue' 事件的超时和监听器。有关更多信息,请参阅 RFC 2616 第 8.2.3 节。

    ¥Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 100-continue', both a timeout and a listener for the 'continue' event should be set. See RFC 2616 Section 8.2.3 for more information.

  • 发送授权标头将覆盖使用 auth 选项来计算基本身份验证。

    ¥Sending an Authorization header will override using the auth option to compute basic authentication.

使用 URL 作为 options 的示例:

¥Example using a URL as options:

const options = new URL('http://abc:xyz@example.com');

const req = http.request(options, (res) => {
  // ...
}); 

在成功的请求中,将按以下顺序触发以下事件:

¥In a successful request, the following events will be emitted in the following order:

  • 'socket'

  • 'response'

    • res 对象上的 'data',任意次数(如果响应正文为空,则根本不会触发 'data',例如,在大多数重定向中)

      ¥'data' any number of times, on the res object ('data' will not be emitted at all if the response body is empty, for instance, in most redirects)

    • res 对象上的 'end'

      ¥'end' on the res object

  • 'close'

在连接错误的情况下,将触发以下事件:

¥In the case of a connection error, the following events will be emitted:

  • 'socket'

  • 'error'

  • 'close'

在收到响应之前过早关闭连接的情况下,将按以下顺序触发以下事件:

¥In the case of a premature connection close before the response is received, the following events will be emitted in the following order:

  • 'socket'

  • 使用具有消息 'Error: socket hang up' 和代码 'ECONNRESET' 的错误的 'error'

    ¥'error' with an error with message 'Error: socket hang up' and code 'ECONNRESET'

  • 'close'

在收到响应之后过早关闭连接的情况下,将按以下顺序触发以下事件:

¥In the case of a premature connection close after the response is received, the following events will be emitted in the following order:

  • 'socket'

  • 'response'

    • res 对象上的 'data',任意次数

      ¥'data' any number of times, on the res object

  • (在此处关闭连接)

    ¥(connection closed here)

  • res 对象上的 'aborted'

    ¥'aborted' on the res object

  • 'close'

  • res 对象上的 'error' 错误消息 'Error: aborted' 和代码 'ECONNRESET'

    ¥'error' on the res object with an error with message 'Error: aborted' and code 'ECONNRESET'

  • res 对象上的 'close'

    ¥'close' on the res object

如果在分配套接字之前调用 req.destroy(),则将按以下顺序触发以下事件:

¥If req.destroy() is called before a socket is assigned, the following events will be emitted in the following order:

  • (在此处调用 req.destroy()

    ¥(req.destroy() called here)

  • 'error' 错误消息 'Error: socket hang up' 和代码 'ECONNRESET',或调用 req.destroy() 时的错误

    ¥'error' with an error with message 'Error: socket hang up' and code 'ECONNRESET', or the error with which req.destroy() was called

  • 'close'

如果在连接成功之前调用 req.destroy(),则将按以下顺序触发以下事件:

¥If req.destroy() is called before the connection succeeds, the following events will be emitted in the following order:

  • 'socket'

  • (在此处调用 req.destroy()

    ¥(req.destroy() called here)

  • 'error' 错误消息 'Error: socket hang up' 和代码 'ECONNRESET',或调用 req.destroy() 时的错误

    ¥'error' with an error with message 'Error: socket hang up' and code 'ECONNRESET', or the error with which req.destroy() was called

  • 'close'

如果在收到响应之后调用 req.destroy(),则将按以下顺序触发以下事件:

¥If req.destroy() is called after the response is received, the following events will be emitted in the following order:

  • 'socket'

  • 'response'

    • res 对象上的 'data',任意次数

      ¥'data' any number of times, on the res object

  • (在此处调用 req.destroy()

    ¥(req.destroy() called here)

  • res 对象上的 'aborted'

    ¥'aborted' on the res object

  • 'close'

  • res 对象上的 'error' 出现消息 'Error: aborted' 和代码 'ECONNRESET' 的错误,或者调用 req.destroy() 时出现的错误

    ¥'error' on the res object with an error with message 'Error: aborted' and code 'ECONNRESET', or the error with which req.destroy() was called

  • res 对象上的 'close'

    ¥'close' on the res object

如果在分配套接字之前调用 req.abort(),则将按以下顺序触发以下事件:

¥If req.abort() is called before a socket is assigned, the following events will be emitted in the following order:

  • (在此处调用 req.abort()

    ¥(req.abort() called here)

  • 'abort'

  • 'close'

如果在连接成功之前调用 req.abort(),则将按以下顺序触发以下事件:

¥If req.abort() is called before the connection succeeds, the following events will be emitted in the following order:

  • 'socket'

  • (在此处调用 req.abort()

    ¥(req.abort() called here)

  • 'abort'

  • 使用具有消息 'Error: socket hang up' 和代码 'ECONNRESET' 的错误的 'error'

    ¥'error' with an error with message 'Error: socket hang up' and code 'ECONNRESET'

  • 'close'

如果在收到响应之后调用 req.abort(),则将按以下顺序触发以下事件:

¥If req.abort() is called after the response is received, the following events will be emitted in the following order:

  • 'socket'

  • 'response'

    • res 对象上的 'data',任意次数

      ¥'data' any number of times, on the res object

  • (在此处调用 req.abort()

    ¥(req.abort() called here)

  • 'abort'

  • res 对象上的 'aborted'

    ¥'aborted' on the res object

  • res 对象上的 'error',使用具有消息 'Error: aborted' 和代码 'ECONNRESET' 的错误。

    ¥'error' on the res object with an error with message 'Error: aborted' and code 'ECONNRESET'.

  • 'close'

  • res 对象上的 'close'

    ¥'close' on the res object

设置 timeout 选项或使用 setTimeout() 函数将不会中止请求或执行除添加 'timeout' 事件外的任何操作。

¥Setting the timeout option or using the setTimeout() function will not abort the request or do anything besides add a 'timeout' event.

传递 AbortSignal,然后在相应的 AbortController 上调用 abort() 的行为方式与在请求中调用 .destroy() 的方式相同。具体来说,'error' 事件将触发错误消息 'AbortError: The operation was aborted'、代码 'ABORT_ERR'cause(如果提供的话)。

¥Passing an AbortSignal and then calling abort() on the corresponding AbortController will behave the same way as calling .destroy() on the request. Specifically, the 'error' event will be emitted with an error with the message 'AbortError: The operation was aborted', the code 'ABORT_ERR' and the cause, if one was provided.