http.request(url[, options][, callback])
url<string> | <URL>options<Object>agent<http.Agent> | <boolean> 控制Agent的行为。可能的值:undefined(默认):对该主机和端口使用http.globalAgent。Agent对象:明确使用传入的Agent。false:导致使用具有默认值的新Agent。
auth<string> 基本认证('user:password')用于计算授权头。createConnection<Function> 一个在未使用agent选项时用于请求的套接字/流的函数。可以用它来避免仅为了重写默认的createConnection函数而创建自定义的Agent类。更多详细信息请参见agent.createConnection()。任何Duplex流都是有效的返回值。defaultPort<number> 该协议的默认端口。默认值: 如果使用Agent则为agent.defaultPort,否则为undefined。family<number> 解析host或hostname时使用的 IP 地址类型。有效值为4或6。如果未指定,将同时使用 IPv4 和 IPv6。headers<Object> 包含请求头的对象。hints<number> 可选dns.lookup()提示。host<string> 要向其发出请求的服务器的域名或 IP 地址。默认值:'localhost'。hostname<string>host的别名。为了支持url.parse(),如果同时指定了host和hostname,将使用hostname。insecureHTTPParser<boolean> 在true时使用不安全的 HTTP 解析器,它可以接受无效的 HTTP 头。应避免使用不安全的解析器。更多信息请参见--insecure-http-parser。默认值:falsejoinDuplicateHeaders<boolean> 它将请求中多个头部的字段行值用,连接,而不是丢弃重复项。有关更多信息,请参见message.headers。默认值:false。localAddress<string> 用于网络连接的本地接口绑定。localPort<number> 本地连接端口。lookup<Function> 自定义查找函数。默认:dns.lookup()。maxHeaderSize<number> 可选择性地覆盖服务器响应中--max-http-header-size(响应头的最大长度,以字节为单位)的值。**默认值:**16384(16 KiB)。method<string> 一个指定 HTTP 请求方法的字符串。默认值:'GET'。path<string> 请求路径。如果有的话,应包括查询字符串。例如:'/index.html?page=12'。当请求路径包含非法字符时,会抛出异常。目前,只拒绝空格,但将来可能会有所变化。默认值:'/'。port<number> 远程服务器端口。**默认值:**如果已设置为defaultPort,否则为80。protocol<string> 要使用的协议。默认:'http:'。setHost<boolean>: 指定是否自动添加Host头。默认为true。signal<AbortSignal>: 可用于中止正在进行的请求的 AbortSignal。socketPath<string> Unix 域套接字。如果指定了host或port中的任何一个,则不能使用,因为它们指定的是 TCP 套接字。timeout<number>:指定套接字超时时间(毫秒)。这将设置套接字连接前的超时时间。uniqueHeaders<Array> 应仅发送一次的请求头列表。如果请求头的值是数组,数组项将使用;连接。
callback<Function>- 返回:<http.ClientRequest>
socket.connect() 中的 options 也受支持。
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 和 options,这些对象将会合并,其中 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 对象。
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.
- 发送“Connection: keep-alive”将通知 Node.js,连接服务器应保持直到下一次请求。
- 发送 'Content-Length' 头将会禁用默认的分块传输编码。
- 发送 'Expect' 头会立即发送请求头。通常,在发送 'Expect: 100-continue' 时,应同时设置超时和
'continue'事件的监听器。有关更多信息,请参阅 RFC 2616 第 8.2.3 节。 - 发送授权头将覆盖使用
auth选项来计算基本身份验证。
使用 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''data'可以在res对象上出现任意次数(如果响应体为空,例如在大多数重定向中,'data'将根本不会被触发)res对象上的'end'
'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',错误信息为'Error: socket hang up',错误代码为'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''data'在res对象上可以出现任意次数
- (连接已关闭)
res对象上的'aborted'res对象上的'error',错误信息为'Error: aborted',错误代码为'ECONNRESET''close'res对象上的'close'
如果在分配套接字之前调用 req.destroy(),将按以下顺序触发以下事件:
🌐 If req.destroy() is called before a socket is assigned, the following
events will be emitted in the following order:
- (此处调用了
req.destroy()) 'error'错误,其消息为'Error: socket hang up',代码为'ECONNRESET',或者是调用req.destroy()时产生的错误'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()) 'error'错误,其消息为'Error: socket hang up',代码为'ECONNRESET',或者是调用req.destroy()时产生的错误'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''data'在res对象上可以出现任意次数
- (此处调用了
req.destroy()) res对象上的'aborted'res对象上的'error'错误,错误信息为'Error: aborted',错误代码为'ECONNRESET',或者是用于调用req.destroy()的错误'close'res对象上的'close'
如果在分配套接字之前调用 req.abort(),将按以下顺序触发以下事件:
🌐 If req.abort() is called before a socket is assigned, the following
events will be emitted in the following order:
- (此处调用了
req.abort()) '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()) 'abort''error',错误信息为'Error: socket hang up',错误代码为'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''data'在res对象上可以出现任意次数
- (此处调用了
req.abort()) 'abort'res对象上的'aborted'res对象上的'error',错误信息为'Error: aborted',错误代码为'ECONNRESET'。'close'res对象上的'close'
设置 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.