原生 Node 开发 Web 服务器

server/2025/2/2 10:13:19/

一、创建基本的 HTTP 服务器

使用 http 模块创建 Web 服务器

javascript">const http = require("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:http://127.0.0.1:3000");});

二、处理不同的 HTTP 请求方法

1. 创建 index.html

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Demo</title></head><body><h1>你好啊</h1><form action="./" method="post"><input type="text" name="username" /><input type="text" name="age" /><input type="submit" value="提交" /></form></body></html>

2. 编辑 index.js

javascript">const http = require("http");const fs = require("fs");const server = http.createServer((req, res) => {if (req.method === "GET") {// 处理GET请求res.writeHead(200, { "Content-Type": "text/html" });fs.readFile("./index.html", "utf8", (err, data) => {if (!err) {res.end(data);}});} else if (req.method === "POST") {// 处理POST请求let data = "";req.on("data", (chunk) => {data += chunk;});req.on("end", () => {res.writeHead(200, { "Content-Type": "text/plain" });res.end(`This is a POST request. Data received: ${data}`);});} else {// 处理其他请求方法res.writeHead(405, { "Content-Type": "text/plain" });res.end("Method Not Allowed");}});// 监听端口server.listen(3000, () => {console.log("Server running:http://127.0.0.1:3000");});

三、路由处理

javascript">const http = require("http");const url = require("url");const server = http.createServer((req, res) => {// 解析URLconst parsedUrl = url.parse(req.url, true);const pathname = parsedUrl.pathname;if (pathname === "/") {// 处理根路径请求res.writeHead(200, { "Content-Type": "text/plain" });res.end("This is the home page");} else if (pathname === "/about") {// 处理/about路径请求res.writeHead(200, { "Content-Type": "text/plain" });res.end("This is the about page");} else {// 处理其他路径请求res.writeHead(404, { "Content-Type": "text/plain" });res.end("Page Not Found");}});server.listen(3000, () => {console.log("Server running on port 3000");});

四、静态文件服务

可以使用`fs`模块来实现静态文件的服务,例如返回 HTML、CSS、JavaScript 等文件。

javascript">const http = require("http");const fs = require("fs");const path = require("path");const url = require("url");const server = http.createServer((req, res) => {// 解析URLconst parsedUrl = url.parse(req.url, true);const pathname = parsedUrl.pathname;// 处理根路径请求,返回index.html文件if (pathname === "/") {const filePath = path.join(__dirname, "index.html");fs.readFile(filePath, (err, data) => {if (err) {res.writeHead(500, { "Content-Type": "text/plain" });res.end("Internal Server Error");} else {res.writeHead(200, { "Content-Type": "text/html" });res.end(data);}});// 处理其他静态文件请求} else {const filePath = path.join(__dirname, pathname);// fs.stat 判断路径对应的是否为文件fs.stat(filePath, (err, stats) => {if (err) {res.writeHead(404, { "Content-Type": "text/plain" });res.end("Page Not Found");} else if (stats.isFile()) {// 如果是文件,则读取并返回文件内容fs.readFile(filePath, (err, data) => {if (err) {res.writeHead(500, { "Content-Type": "text/plain" });res.end("Internal Server Error");} else {// 根据文件扩展名设置正确的Content-Typeconst extname = path.extname(filePath);let contentType = "text/plain";if (extname === ".html") {contentType = "text/html";} else if (extname === ".css") {contentType = "text/css";} else if (extname === ".js") {contentType = "application/javascript";}res.writeHead(200, { "Content-Type": contentType });res.end(data);}});} else {res.writeHead(404, { "Content-Type": "text/plain" });res.end("Page Not Found");}});}});server.listen(3000, () => {console.log("Server running on port 3000");});


http://www.ppmy.cn/server/164301.html

相关文章

UART IIC 和 SPI 三种总线

总线是连接多个部件的数据传输线&#xff0c;是各部件共享的传输介质 总线分为片内总线和片外总线&#xff0c;片内总线负责连接处理器内核和外设的总线&#xff0c;在芯片内部&#xff1b;片外总线负责连接芯片和其他芯片或者模块。 UART(Universal Asynchronous Receiver/T…

【25考研】中科院软件考研复试难度分析!

中科院软件复试不需要上机&#xff01;且对专业综合能力要求较高&#xff01;提醒同学一定要认真复习&#xff01; 一、复试内容 二、参考书目 官方并未明确给出&#xff0c;建议同学参考初试书目&#xff1a; 1&#xff09;《数据结构&#xff08;C语言版&#xff09;》严蔚…

【Linux】CentOS8虚拟机的基本环境配置

1. 引子 根据前几章的教学搭建了一个Linux的学习环境后&#xff0c;下面就要开始进行Linux系统环境的配置了。这部分可是不能跳过的哦&#xff01;虽然网上有自动化配置的脚本&#xff0c;但只有自己尝试过配置&#xff0c;后续遇到问题才能“不求人”。 后续所有的操作都将在…

Unity敌人逻辑笔记

写ai逻辑基本上都需要状态机。因为懒得手搓状态机&#xff0c;所以选择直接用动画状态机当逻辑状态机用。 架构设计 因为敌人的根节点已经有一个animator控制动画&#xff0c;只能增加一个子节点AI&#xff0c;给它加一个animator指向逻辑“动画”状态机。还有一个脚本&#…

文献阅读 250201-The carbon budget of China: 1980–2021

The carbon budget of China: 1980–2021 来自 <https://www.sciencedirect.com/science/article/pii/S2095927323007703> 中国碳预算&#xff1a;1980–2021 年 ## Abstract: Using state-of-the-art datasets and models, this study comprehensively estimated the an…

MySQL基本架构SQL语句在数据库框架中的执行流程数据库的三范式

MySQL基本架构图&#xff1a; MySQL主要分为Server层和存储引擎层 Server层&#xff1a; 连接器&#xff1a;连接客户端&#xff0c;获取权限&#xff0c;管理连接 查询缓存&#xff08;可选&#xff09;&#xff1a;在执行查询语句之前会先到查询缓存中查看是否执行过这条语…

每日一道算法题

题目&#xff1a;单词接龙 II 给定两个单词&#xff08;beginWord 和 endWord&#xff09;和一个字典 wordList&#xff0c;找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则&#xff1a; 每次转换只能改变一个字母。转换过程中的中间单词必须是字典中的…

Ubuntu安装VMware17

安装 下载本文的附件&#xff0c;之后执行 sudo chmod x VMware-Workstation-Full-17.5.2-23775571.x86_64.bundle sudo ./VMware-Workstation-Full-17.5.2-23775571.x86_64.bundle安装注意事项&#xff1a; 跳过账户登录的办法&#xff1a;断开网络 可能出现的问题以及解决…