跳到主要内容

http

一、http


HTTP 核心模块是 Node.js 网络的关键模块。

二、http.METHODS


三、http.STATUS_CODES


四、http.createServer([options][, requestListener])


4.1 认识

4.2 语法

const http = require('node:http');

const server = http.createServer([options][, requestListener])
  • options:

    • connectionsCheckingInterval:以毫秒为单位设置间隔值,以检查不完整请求中的请求和标头超时。默认值:30000

    • headersTimeout:设置从客户端接收完整 HTTP 标头的超时值,以毫秒为单位。有关详细信息,请参阅 server.headersTimeout。默认值:60000

    • highWaterMark <number>: 可选择覆盖所有 socketreadableHighWaterMarkwritableHighWaterMark。这会影响 IncomingMessageServerResponsehighWaterMark 属性。默认值:参见 stream.getDefaultHighWaterMark()

    • insecureHTTPParser <boolean>: 如果设置为 true,它将使用启用了宽大标志的 HTTP 解析器。应避免使用不安全的解析器。有关详细信息,请参阅 --insecure-http-parser。默认值:false

    • IncomingMessage <http.IncomingMessage>: 指定要使用的 IncomingMessage 类。用于扩展原始的 IncomingMessage。默认值:IncomingMessage

    • joinDuplicateHeaders <boolean>: 如果设置为 true,则此选项允许使用逗号 (, ) 连接请求中多个标头的字段行值,而不是丢弃重复项。欲了解更多信息,请参阅 message.headers。默认值:false

    • keepAlive <boolean>: 如果设置为 true,则在收到新的传入连接后立即启用套接字上的保持活动功能,与 [socket.setKeepAlive([enable][, initialDelay])][socket.setKeepAlive(enable, initialDelay)] 中的操作类似。默认值:false

    • keepAliveInitialDelay <number>: 如果设置为正数,则它会设置在空闲套接字上发送第一个保持活跃探测之前的初始延迟。默认值:0

    • keepAliveTimeout: 在完成写入最后一个响应之后,在套接字将被销毁之前,服务器需要等待额外传入数据的不活动毫秒数。有关详细信息,请参阅 server.keepAliveTimeout。默认值:5000

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

    • noDelay <boolean>: 如果设置为 true,则它会在收到新的传入连接后立即禁用 Nagle 算法。默认值:true

    • requestTimeout:设置从客户端接收整个请求的超时值(以毫秒为单位)。有关详细信息,请参阅 server.requestTimeout。默认值:300000

    • requireHostHeader <boolean>: 如果设置为 true,它会强制服务器以 400(错误请求)状态代码响应任何缺少主机标头(按照规范的规定)的 HTTP/1.1 请求消息。默认值:true

    • ServerResponse <http.ServerResponse>: 指定要使用的 ServerResponse 类。用于扩展原始的 ServerResponse。默认值:ServerResponse

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

    • rejectNonStandardBodyWrites <boolean>: 如果设置为 true,则在写入没有正文的 HTTP 响应时会抛出错误。默认值:false

  • requestListener: requestListener 是自动添加到 request 事件的函数。

  • server: 返回 http.Server 的新实例。

4.3 场景

一、使用 http.createServer 实现 HTTP 服务器

const http = require('node:http');

const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});

server.listen(8000);
const http = require('node:http');

const server = http.createServer();

server.on('request', (request, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});

server.listen(8000);

二、使用Koahttp.createServer 实现 HTTP 服务器: Koa 使用 http.createServer() 方法来创建 HTTP 服务器。通常会看到 Koa 通过 app.callback() 方法将 Koa 应用程序转换为一个可以处理 HTTP 请求的回调函数,http.createServer() 使用这个回调来处理请求。

const Koa = require("koa");
const http = require("http");

const app = new Koa();
const server = http.createServer(app.callback());

app.use((ctx) => {
ctx.type = "application/json";

ctx.body = JSON.stringify({
data: "Hello World!",
});
});

server.listen(8000, () => {
console.log("Koa HTTP Server is running on port 8000");
});

三、使用Expresshttp.createServer 实现 HTTP 服务器: 将 Express 应用程序作为回调传递给 http.createServer()Express 会处理请求并生成响应。

const express = require("express");
const http = require("http");

const app = express();
const server = http.createServer(app);

app.get("/", (req, res) => {
res.send("Hello, Express with HTTP!");
});

server.listen(8000, () => {
console.log("Express HTTP Server is running on port 8000");
});

五、http.get(options[, callback])


六、http.get(url[, options][, callback])


七、http.globalAgent


八、http.maxHeaderSize


九、http.request(options[, callback])


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


10.1 认识

10.2 语法

const req = http.request(options[, callback])#

const req = http.request(url[, options][, callback])
  • url:

  • options

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

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

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

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

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

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

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

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

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

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

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

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

    • insecureHTTPParser <boolean>: 如果设置为 true,它将使用启用了宽大标志的 HTTP 解析器。应避免使用不安全的解析器。有关详细信息,请参阅 --insecure-http-parser。默认值:false

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

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

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

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

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

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

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

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

  • callback

  • req

十一、http.validateHeaderName(name[, label])


十二、http.validateHeaderValue(name, value)


十三、http.setMaxIdleHTTPParsers(max)


参考资料


Node.js 中文网