Node.js HTTP 模块是 Node.js 中用于创建 HTTP 服务器和客户端的核心模块。它提供了创建服务器、客户端、代理和流式传输等功能。

功能概述

  • 创建服务器:使用 http.createServer() 方法可以创建一个 HTTP 服务器。
  • 请求处理:服务器可以接收 HTTP 请求,并通过回调函数处理这些请求。
  • 响应发送:服务器可以发送 HTTP 响应给客户端。
  • 客户端请求:使用 http.request() 方法可以创建一个 HTTP 客户端,用于发送请求。

示例代码

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('<h1>Welcome to the Node.js HTTP Server</h1>');
  }
});

server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

扩展阅读

更多关于 Node.js HTTP 模块的信息,可以参考 Node.js 官方文档

Node.js Logo