当前位置: 首页 > article >正文

Node.js 的 http 模块

http 模块是 Node.js 的核心模块之一,它提供了许多方法用于创建 HTTP 服务器、发送 HTTP 请求等。

http 模块的函数

创建一个 http 服务器

http.createServer([requestListener])

参数:

  • requestListener:可选参数,接收请求的回调函数。requestListener 会处理每个 HTTP 请求,并接收两个参数:req(请求对象)和 res(响应对象)。

返回值:

  • 返回一个 HTTP 服务器实例(http.Server 对象)。

示例:

import http from 'http';

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });    // 服务器返回的数据格式
    res.end('Hello, World!');    // 返回的数据
});

设置 http 服务器的监听端口

http.Server.listen([port[, hostname[, backlog[, callback]]]])

参数:

  • port:要监听的端口。
  • hostname:可选,指定要绑定的主机名(默认为 localhost)。
  • backlog:可选,指定监听队列的长度。
  • callback:可选,当服务器启动成功后执行的回调函数。

返回值:

  • 返回 http.Server 实例。

示例:

import http from 'http';

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, World!');
});
server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

关闭 http 服务器

http.Server.close([callback])

close 不会立即断开连接,而是等待现有请求执行完成。

参数:

  • callback:可选,当服务器关闭时调用的回调函数。

返回值: 无。

示例:

import http from 'http';

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, World!');
});
server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});
// 模拟服务器关闭
setTimeout(() => {
    server.close(() => {
        console.log('Server is closed.');
    });
}, 5000); // 5秒后关闭服务器

设置服务器超时时间

http.Server.setTimeout(msecs[, callback])

参数:

  • msecs:超时时间(以毫秒为单位)。
  • callback:可选,在超时事件发生时调用的回调函数。

返回值:

  • 返回 http.Server 实例。

示例:

import http from 'http';

const server = http.createServer((req, res) => {
    setTimeout(() => {

    }, 10000);
});
server.listen(3000);
server.setTimeout(5000, () => {
    console.log('Server timeout');
});

设置服务器可以注册的最大监听器数量

http.Server.setMaxListeners(n)

意思是一个事件,有几个监听这个事件的函数?默认最大数量是10。设置太多容易发生内存泄漏。

参数:

  • n:最大监听器数量。

返回值:

  • 返回 http.Server 实例。

示例:

import http from 'http';

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, World!');
});
server.setMaxListeners(20);

发送一个 http 请求

http.request(options[, callback])

参数:

  • options:请求的配置对象(例如:hostname, port, method, headers 等)。
  • callback:可选,处理响应的回调函数。

返回值: 

  • 返回一个客户端请求对象(http.ClientRequest 对象)。

示例:

import http from 'http';

const options = {
    hostname: '127.0.0.1',
    port: 3000,
    path: '/',
    method: 'GET'
};
const req = http.request(options, (res) => {
    let data = '';              // 创建一个变量,用于接收服务器的响应数据。
    res.on('data', (chunk) => { // res 对象是服务器的响应对象,on 监听 'data' 事件,chunk 是每次接收到的数据块
        data += chunk;          // 每次收到数据块时,都会将其追加到 data 字符串中,最终构成完整的响应数据
    });
    res.on('end', () => {       // 注册了一个 'end' 事件的监听器,当整个响应的数据接收完毕时,'end' 事件会被触发。在此回调函数内,输出完整的响应数据。
        console.log(data);
    });
});
req.end();  // 结束请求并告知服务器请求已经完成。

示例:        发送一个 post 请求

import http from 'http';

// 配置请求选项
const options = {
    hostname: '127.0.0.1',
    port: 3000,
    path: '/',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',  // 表单数据类型
        'Content-Length': Buffer.byteLength('name=John&age=30')  // 请求体长度,即发送数据的字节长度
        // 'Content-Type': 'application/json',  // 请求体类型,json 类型
        // 'Content-Length': Buffer.byteLength(JSON.stringify({ name: 'John', age: 30 }))  // 请求体长度,json 类型
    }
};

// 创建 POST 请求
const req = http.request(options, (res) => {
    let data = '';
    res.on('data', (chunk) => {
        data += chunk;
    });
    res.on('end', () => {
        console.log('Response:', data);
    });
});

req.on('error', (error) => {
    console.error(`Request error: ${error.message}`);
});

// 发送表单数据
const postData = 'name=John&age=30';    // 实际发送的数据
// const postData = JSON.stringify({ name: 'John', age: 30 });  // json 类型
req.write(postData);

// 结束请求
req.end();

发送一个 get 请求

http.get(options[, callback])

参数:

  • options:请求的配置对象(hostname, port, path, headers 等)。
  • callback:处理响应的回调函数。

返回值:

  • 返回一个 http.ClientRequest 对象。

示例:

import http from 'http';

http.get('http://127.0.0.1:3000', (res) => {
    let data = '';                  // 创建一个变量,用于接收服务器的响应数据。
    res.on('data', (chunk) => {     // res 对象是服务器的响应对象,on 监听 'data' 事件,chunk 是每次接收到的数据块
        data += chunk;              // 每次收到数据块时,都会将其追加到 data 字符串中,最终构成完整的响应数据
    });
    res.on('end', () => {           // 注册了一个 'end' 事件的监听器,当整个响应的数据接收完毕时,'end' 事件会被触发。在此回调函数内,输出完整的响应数据。
        console.log(data);
    });
});

获取当前服务器的连接数

http.Server.getConnections(callback)

参数:

  • callback:回调函数,接收两个参数:err(错误对象)和 count(连接数)。

返回值: 无。

示例:

import http from 'http';

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, World!');
});
server.listen(3000);
setTimeout(() => {
    server.getConnections((err, count) => {
        console.log('Current connections:', count);
    });
}, 5000);


http://www.kler.cn/a/556286.html

相关文章:

  • Vue 3 和 Vite 从零开始搭建项目的详细步骤
  • 在 Flutter 中实现文件读写
  • LeetCode刷题---二分查找---441
  • Web Scraper,强大的浏览器爬虫插件!
  • 软件架构设计:架构风格
  • Python Cookbook-2.4 从文件中读取指定的行
  • 朴素贝叶斯法
  • AB-02 AUTOSAR builder创建工程
  • c#编程:学习Linq,重几个简单示例开始
  • 优化 Flink 消费 Kafka 数据的速度:实战指南
  • 游戏引擎学习第113天
  • Prompt-提示词越狱
  • 如何用deepseek快速生成思维导图和流程图?
  • 2024系统编程语言风云变幻:Rust持续领跑,Zig与Ada异军突起
  • 《论系统需求分析方法》写作心得 - 系统分析师
  • Dify怎么创建数据交易的智能体
  • 内容中台重构智能服务:人工智能技术驱动精准决策
  • 中诺CHINO-E G076大容量录音电话产品使用注意事项
  • 推荐几款SpringBoot项目手脚架
  • JavaScript 中 Image() 对象的属性和方法详解