原生 Node 开发 Web 服务器

news/2025/2/3 14:11:43/

一、创建基本的 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/news/1568972.html

相关文章

论文阅读(十四):贝叶斯网络在全基因组DNA甲基化研究中的应用

1.论文链接&#xff1a;Bayesian Networks in the Study of Genome-wide DNA Methylation 摘要&#xff1a; 本章探讨了贝叶斯网络在基因组规模的脱氧核糖核酸&#xff08;DNA&#xff09;甲基化研究中的应用。它首先描述了DNA甲基化的基因组规模注释的不同实验方法。详细介绍…

【华为OD-E卷 - 磁盘容量排序 100分(python、java、c++、js、c)】

【华为OD-E卷 - 磁盘容量排序 100分&#xff08;python、java、c、js、c&#xff09;】 题目 磁盘的容量单位常用的有M&#xff0c;G&#xff0c;T这三个等级&#xff0c; 它们之间的换算关系为1T 1024G&#xff0c;1G 1024M&#xff0c; 现在给定n块磁盘的容量&#xff0c…

流处理 CompletableFuture

专栏系列文章地址&#xff1a;https://blog.csdn.net/qq_26437925/article/details/145290162 本文目标&#xff1a; 掌握&#xff1a;流处理 & CompletableFuture的使用 目录 直接例子看同步和异步处理的区别普通流处理进行批量查询批量查询1&#xff1a;并行流操作批量…

Xposed-Hook

配置 Xposed 模块的 AndroidManifest.xml&#xff1a; <?xml version"1.0" encoding"utf-8"?> <manifest xmlns:android"http://schemas.android.com/apk/res/android"package"your.package.name"><applicationandr…

我的世界(Minecraft)计算器python源码

我的世界(Minecraft)计算器python源码 1.介绍 使用教程 博客&#xff1a;【Python】python实现我的世界(Minecraft)计算器视频&#xff1a;Python实现我的世界(Minecraft)计算器(附源码与教程) 2.源码 文件一 # CreateBigScreen.py (创建大屏幕并返回大屏幕坐标)from m…

javaweb实训:购物商城系统项目

包括各类需求文档&#xff0c;任务计划&#xff0c;ppt&#xff0c;项目源代码&#xff0c;数据库文件&#xff0c;包括网站前后台&#xff01;唯一缺憾是面向初学者的&#xff0c;没怎么用框架。购物商城系统项目 文件列表 112购物商城系统项目/(1)需求说明书/112购物商城系统…

高清种子资源获取指南 | ✈️@seedlinkbot

在如今的数字时代&#xff0c;高清影视、音乐、游戏等资源的获取方式不断丰富。对于追求高质量资源的用户而言&#xff0c;一个高效的资源分享平台至关重要。而 ✈️seedlinkbot 正是这样一个便捷的资源获取工具&#xff0c;为用户提供高质量的种子资源索引和下载信息。 1. ✈️…

单细胞分析基础-第一节 数据质控、降维聚类

scRNA_pipeline\1.Seurat 生物技能树 可进官网查询 添加链接描述 分析流程 准备:R包安装 options("repos"="https://mirrors.ustc.edu.cn/CRAN/") if(!require("BiocManager")) install.packages("BiocManager",update = F,ask =…