概念:http 是 Node.js 内置的核心模块,用于创建 HTTP 服务器 和 处理 HTTP 请求 / 响应,是后端开发中搭建 Web 服务的基础。
 一、http 模块的核心作用
创建能接收浏览器 / 客户端请求的 HTTP 服务器;
解析客户端发送的 请求信息(如 URL、参数、请求方法);
向客户端返回 响应内容(如 HTML、文本、文件等);
案例一:创建第一个 HTTP 服务器
步骤一:创建一个server.js文件
const http = require('http')

const server = http.createServer((req,res) => {res.setHeader('Content-Type','text/plain;charset=utf-8');

    res.end('hello node.js HTTP 服务器!');

});

server.listen(3000, () => {

    console.log('服务器启动成功!可访问:http://localhost:3000');

});

步骤 2:运行服务器并访问
终端进入文件所在目录,运行命令:
node server.js
AI写代码
终端显示 服务器启动成功!可访问:http://localhost:3000 表示启动成功;
打开浏览器,访问 http://localhost:3000,页面会显示:
Hello Node.js HTTP 服务器!
AI写代码
案例二:用 http 服务器托管你的时钟案例
const http = require('http')

const fs = require('fs')

const path = require('path');

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

    let url = req.url;

    if(url === '/') {

        url = 'index.html';

    }

    const filePath = path.join(__dirname,url);

    fs.readFile(filePath,(err,data) => {

        if (err) {

            res.writeHead(404,{'Content-Type':'text/plain;charset=utf-8'});

            res.end('文件不存在:' + url)

        }else{

            if(url.endsWith('.html')) {

                res.setHeader('Content-Type','text/html;charset=utf-8');

            }else if (url.endsWith('.css')) {

        res.setHeader('Content-Type', 'text/css; charset=utf-8');

      } else if (url.endsWith('.js')) {

        res.setHeader('Content-Type', 'text/javascript; charset=utf-8');

      }

      // 返回文件内容

      res.end(data);

    }

  });

});

server.listen(3000, () => {

    console.log('服务器启动成功!可访问:http://localhost:3000');

});

核心知识点总结
创建服务器:http.createServer(回调函数),回调函数处理每次请求;
请求与响应:
req(请求):包含客户端信息(如 req.url 是请求路径);
res(响应):用于返回内容(res.setHeader() 设置响应头,res.end() 发送内容);
启动服务器:server.listen(端口, 回调),通过 http://localhost:端口 访问;
静态文件托管:结合 fs 和 path 模块,根据请求路径读取对应文件并返回。
 

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐