Node.js Web服务器开发实战:从基础到数据库集成

1. 引言

Web 服务器是互联网的基石,它负责处理客户端的请求,并返回相应的资源或数据。本文将介绍 Web 服务器的基本概念、关键组件以及如何开发一个简单的 Web 服务器。

2. Web 服务器概述

Web 服务器的主要职责包括:

  • 监听客户端请求(通常是 HTTP/HTTPS 请求)。
  • 解析请求并处理相应的逻辑。
  • 访问服务器上的资源或数据库。
  • 生成响应并返回给客户端。

常见的 Web 服务器有 Nginx、Apache、Tomcat,以及一些轻量级服务器如 Express(Node.js)和 Flask(Python)。

3. Web 服务器关键组件

3.1 服务器架构

Web 服务器通常采用 C/S(Client-Server)架构,主要包含以下组件:

  • 监听端口:服务器通常监听 80(HTTP)或 443(HTTPS)端口。
  • 请求解析器:解析客户端的 HTTP 请求,包括方法、URL、Headers 等。
  • 路由处理器:根据请求的路径,调用相应的业务逻辑。
  • 响应生成器:根据请求结果,返回 HTML、JSON 或其他格式的数据。
  • 中间件(可选):用于身份验证、日志记录、缓存等。

3.2 HTTP 协议基础

HTTP(HyperText Transfer Protocol)是 Web 服务器与客户端通信的基础协议,包括:

  • 请求方法:GET、POST、PUT、DELETE、PATCH 等。
  • 状态码:如 200(成功)、404(未找到)、500(服务器错误)。
  • 头部信息(Headers) :用于传输元信息,如 Content-TypeAuthorization
  • 消息体(Body) :POST/PUT 请求可能包含请求数据,如 JSON、XML。

4. 使用 Node.js 开发简单的 Web 服务器

接下来,我们使用 Node.js 内置的 http 模块开发一个简单的 Web 服务器。

ini 复制代码
const http = require('http');
const PORT = 3000;

const server = http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello, World!');
});

server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/`);
});

5. 进阶优化

5.1 读写文件

使用 fs 模块可以在服务器上读写文件。

读取文件

javascript 复制代码
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    console.log('File content:', data);
});

写入文件

javascript 复制代码
fs.writeFile('output.txt', 'Hello, Web Server!', (err) => {
    if (err) {
        console.error('Error writing file:', err);
        return;
    }
    console.log('File written successfully');
});

5.2 连接数据库

可以使用 mysql2mongoose 连接 MySQL 或 MongoDB 数据库。

连接 MySQL

php 复制代码
const mysql = require('mysql2');
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'test_db'
});

connection.connect(err => {
    if (err) {
        console.error('Database connection failed:', err);
        return;
    }
    console.log('Connected to MySQL database');
});

查询数据

javascript 复制代码
connection.query('SELECT * FROM users', (err, results) => {
    if (err) {
        console.error('Query error:', err);
        return;
    }
    console.log('User data:', results);
});

连接 MongoDB

javascript 复制代码
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test_db', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('Connected to MongoDB'))
    .catch(err => console.error('MongoDB connection error:', err));

5.3 从前端请求到写入数据库的完整示例

1. 前端代码(发送请求)

javascript 复制代码
fetch('http://localhost:3000/api/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ name: 'John Doe', email: 'john@example.com' })
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));

2. 后端代码(Express 处理请求并存入数据库)

php 复制代码
const express = require('express');
const mysql = require('mysql2');
const bodyParser = require('body-parser');
const session = require('express-session');

const app = express();
app.use(bodyParser.json());
app.use(session({
    secret: 'mySecretKey',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false }
}));

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'test_db'
});

connection.connect(err => {
    if (err) {
        console.error('Database connection failed:', err);
        return;
    }
    console.log('Connected to MySQL database');
});

app.post('/api/users', (req, res) => {
    const { name, email } = req.body;
    req.session.user = { name, email };
    connection.query('INSERT INTO users (name, email) VALUES (?, ?)', [name, email], (err, result) => {
        if (err) {
            res.status(500).json({ error: 'Database insert failed' });
            return;
        }
        res.json({ message: 'User added successfully', id: result.insertId, session: req.session.user });
    });
});

app.get('/api/session', (req, res) => {
    if (req.session.user) {
        res.json({ sessionData: req.session.user });
    } else {
        res.json({ message: 'No active session' });
    }
});

app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});

6. 总结

本文介绍了 Web 服务器的基础知识,包括其主要功能、关键组件,以及如何使用 Node.js 构建一个简单的 Web 服务器。同时,我们扩展了 Web 服务器的功能,涵盖了文件读写、数据库连接,并提供了一个完整的前后端交互示例,以及会话控制功能,进一步提升 Web 服务器的应用能力。

相关推荐
brzhang几秒前
别再梭哈 Curosr 了!这 AI 神器直接把需求、架构、任务一条龙全干了!
前端·后端·架构
Kagol9 分钟前
TinyEditor v4.0 alpha 版本发布,更强大的表格、更丰富的表情、体验更好的图片/视频/文件上传功能
前端·开源
安妮的心动录15 分钟前
安妮的2025 Q2 Review
后端·程序员
程序员爱钓鱼15 分钟前
Go语言数组排序(冒泡排序法)—— 用最直观的方式掌握排序算法
后端·google·go
然我18 分钟前
路由还能这么玩?从懒加载到路由守卫,手把手带你解锁 React Router 进阶技巧
前端·react.js·面试
Victor3561 小时前
MySQL(140)如何解决外键约束冲突?
后端
Victor3561 小时前
MySQL(139)如何处理MySQL字符编码问题?
后端
良木林1 小时前
JavaScript书写基础和基本数据类型
开发语言·前端·javascript
007php0072 小时前
服务器上PHP环境安装与更新版本和扩展(安装PHP、Nginx、Redis、Swoole和OPcache)
运维·服务器·后端·nginx·golang·测试用例·php