搭建Node.js服务器

1.基础HTTP服务器:
  • 添加了路由处理
  • 添加了404错误处理
  • 添加了服务器错误监听
2.静态资源服务器:
  • 使用异步文件操作
  • 支持目录自动索引(默认加载 index.html)
  • 自动检测文件类型并设置正确Content-Type
  • 更完善的错误处理
3.处理GET请求参数
  • 提供了一个HTML表单用于测试
  • 使用url模块解析URL和查询参数
  • 清晰展示接收到的GET参数
4.处理POST请求参数:
  • 提供了一个HTML表单用于测试
  • 使用流的方式处理POST数据
  • 正确解析表单数据
  • 清晰展示接收到的POST参数

一、HTTP模块

html 复制代码
const http = require("http");

// 创建服务器实例
const app = http.createServer((req, res) => {
    // 设置响应头,指定内容类型和编码
    res.setHeader("Content-Type", "text/html;charset=utf-8");
    
    // 根据请求路径返回不同内容
    switch (req.url) {
        case "/":
            res.end("欢迎访问主页!");
            break;
        case "/about":
            res.end("这是关于页面!");
            break;
        default:
            res.statusCode = 404;
            res.end("404 - 页面未找到");
    }
});

// 监听端口并启动服务器
app.listen(5000, () => {
    console.log("服务器已启动!监听在 http://localhost:5000");
});

// 添加错误处理
app.on("error", (error) => {
    console.error(`服务器启动失败: ${error.message}`);
});    

二、静态资源服务器

html 复制代码
const http = require("http");
const fs = require("fs").promises;
const path = require("path");

// 定义静态资源目录
const STATIC_DIR = path.join(__dirname, "static");

// 内容类型映射表
const CONTENT_TYPES = {
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/javascript",
    ".json": "application/json",
    ".png": "image/png",
    ".jpg": "image/jpeg",
    ".gif": "image/gif",
    ".svg": "image/svg+xml",
    ".txt": "text/plain"
};

const app = http.createServer(async (req, res) => {
    try {
        // 构建文件路径
        let filePath = path.join(STATIC_DIR, req.url === "/" ? "index.html" : req.url);
        
        // 检查文件是否存在
        await fs.access(filePath);
        
        // 获取文件状态
        const stat = await fs.stat(filePath);
        
        if (stat.isDirectory()) {
            // 如果是目录,尝试默认文件
            filePath = path.join(filePath, "index.html");
            await fs.access(filePath);
        }
        
        // 获取文件扩展名并确定内容类型
        const extname = path.extname(filePath);
        const contentType = CONTENT_TYPES[extname] || "application/octet-stream";
        
        // 设置响应头并发送文件内容
        res.setHeader("Content-Type", contentType);
        const fileContent = await fs.readFile(filePath);
        res.end(fileContent);
    } catch (error) {
        // 处理错误
        res.statusCode = 404;
        res.end("404 - 文件未找到");
    }
});

app.listen(3000, () => {
    console.log("服务器监听在 http://localhost:3000");
});    

三、服务器获取get请求参数

在./static下面写一个index.html页面,页面中发送一个get请求

html 复制代码
const http = require("http");
const url = require("url");
const qs = require("querystring");

const app = http.createServer((req, res) => {
    res.setHeader("Content-Type", "text/html;charset=utf-8");
    
    // 解析URL和查询参数
    const parsedUrl = url.parse(req.url, true);
    const pathname = parsedUrl.pathname;
    const query = parsedUrl.query;
    
    if (pathname === "/") {
        // 返回表单页面
        const formHtml = `
            <form method="GET" action="/api">
                <input type="text" name="username" placeholder="用户名">
                <input type="password" name="password" placeholder="密码">
                <button type="submit">提交</button>
            </form>
        `;
        res.end(formHtml);
    } else if (pathname === "/api") {
        // 处理GET请求参数
        res.end(`收到GET请求,参数:${JSON.stringify(query)}`);
    } else {
        res.statusCode = 404;
        res.end("404 - 页面未找到");
    }
});

app.listen(8888, () => {
    console.log("服务器已启动!地址为: http://localhost:8888");
});    

四、服务器获取post请求参数

获取post请求的参数,通过给req绑定事件和end事件,来获取监听的参数,data事件一个接收的事件,end事件 当post请求的参数都接收完毕,就出发end事件

html 复制代码
const http = require("http");
const qs = require("querystring");

const app = http.createServer((req, res) => {
    res.setHeader("Content-Type", "text/html;charset=utf-8");
    
    if (req.url === "/") {
        // 返回表单页面
        const formHtml = `
            <form method="POST" action="/api">
                <input type="text" name="username" placeholder="用户名">
                <input type="password" name="password" placeholder="密码">
                <button type="submit">提交</button>
            </form>
        `;
        res.end(formHtml);
    } else if (req.url === "/api" && req.method === "POST") {
        // 处理POST请求
        let body = "";
        
        // 监听data事件,收集数据块
        req.on("data", (chunk) => {
            body += chunk.toString();
        });
        
        // 监听end事件,数据接收完成
        req.on("end", () => {
            // 解析表单数据
            const formData = qs.parse(body);
            
            // 返回处理结果
            res.end(`收到POST请求,参数:${JSON.stringify(formData)}`);
        });
    } else {
        res.statusCode = 404;
        res.end("404 - 页面未找到");
    }
});

app.listen(8888, () => {
    console.log("服务器已启动!地址为: http://localhost:8888");
});    

每个步骤的代码都可以独立运行,并且包含了必要的注释以便理解

相关推荐
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ9 分钟前
Linux 下使用 vim 文本编辑器时的操作指令
linux·运维·vim
胡耀超40 分钟前
GraphRAG Docker化部署,接入本地Ollama完整技术指南:从零基础到生产部署的系统性知识体系
运维·docker·容器·大模型·知识图谱·rag·ollama
hryyx1 小时前
Linux磁盘限速(Ubuntu24实测)
linux·运维·服务器
阿巴~阿巴~1 小时前
Linux进程状态实战指南:转换关系、监控命令与状态解析
linux·运维·服务器
cpsvps2 小时前
香港服务器Python自动化巡检脚本开发与邮件告警集成
服务器·python·自动化
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ2 小时前
linux打包指令和移动指令
linux·运维·服务器
mini小新2 小时前
PostgreSQL如何进行跨服务器迁移数据
服务器·数据库·postgresql·数据迁移
阿蒙Amon2 小时前
C#日期、时间和时区:全球化应用的时间处理艺术
java·服务器·c#
羑悻的小杀马特3 小时前
一扇门铃,万向感应——用 eventfd 实现零延迟通信
linux·运维·服务器·eventfd
豆是浪个7 小时前
Linux(Centos 7.6)命令详解:usermod
linux·运维·centos