原生 Node 开发 Web 服务器

一、创建基本的 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

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) => {

  // 解析URL

  const 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) => {

  // 解析URL

  const 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-Type

            const 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");

});
相关推荐
JosieBook1 天前
【远程运维】Linux 远程连接 Windows 好用的软件:MobaXterm 实战指南
linux·运维·windows
2501_915918411 天前
Web 前端可视化开发工具对比 低代码平台、可视化搭建工具、前端可视化编辑器与在线可视化开发环境的实战分析
前端·低代码·ios·小程序·uni-app·编辑器·iphone
程序员的世界你不懂1 天前
【Flask】测试平台开发,新增说明书编写和展示功能 第二十三篇
java·前端·数据库
索迪迈科技1 天前
网络请求库——Axios库深度解析
前端·网络·vue.js·北京百思可瑞教育·百思可瑞教育
gnip1 天前
JavaScript二叉树相关概念
前端
鳄鱼杆1 天前
服务器 | Docker应用开发与部署的实践以及阿里云镜像加速配置
服务器·阿里云·docker
羚羊角uou1 天前
【Linux】命名管道
linux·运维·服务器
IT 小阿姨(数据库)1 天前
PgSQL监控死元组和自动清理状态的SQL语句执行报错ERROR: division by zero原因分析和解决方法
linux·运维·数据库·sql·postgresql·centos
一朵梨花压海棠go1 天前
html+js实现表格本地筛选
开发语言·javascript·html·ecmascript
曾经的三心草1 天前
Python2-工具安装使用-anaconda-jupyter-PyCharm-Matplotlib
android·java·服务器