Node.js的http模块
- 手机
- 2025-08-31 20:48:02

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- -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);Node.js的http模块由讯客互联手机栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“Node.js的http模块”