Node.js 网站开发实战,从入门到部署
本文目录导读:
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,它使得开发者能够使用 JavaScript 编写服务器端代码,由于其事件驱动、非阻塞 I/O 的特性,Node.js 特别适合构建高性能、可扩展的网络应用,本文将带领你从零开始,实战开发一个完整的 Node.js 网站,涵盖项目搭建、数据库集成、API 开发、前端渲染以及最终部署的全过程。

准备工作
在开始之前,确保你的开发环境已经安装了以下工具:
- Node.js(建议使用 LTS 版本)
- npm(Node.js 包管理器)
- 代码编辑器(如 VS Code)
- 数据库(本文使用 MongoDB)
1 初始化项目
创建一个新的项目目录并初始化 Node.js 项目:
mkdir node-website cd node-website npm init -y
这将生成一个 package.json 文件,用于管理项目依赖。
2 安装必要的依赖
我们将使用 Express.js 作为后端框架,同时安装其他常用库:
npm install express mongoose body-parser ejs
- Express.js:轻量级的 Node.js Web 框架
- Mongoose:MongoDB 的 ODM(对象文档映射)
- body-parser:解析 HTTP 请求体
- ejs:模板引擎,用于服务器端渲染
搭建基础服务器
1 创建 Express 应用
在项目根目录下创建 app.js,并编写以下代码:
const express = require('express');
const app = express();
const PORT = 3000;
// 设置视图引擎为 EJS
app.set('view engine', 'ejs');
// 静态文件服务
app.use(express.static('public'));
// 解析 POST 请求
app.use(express.urlencoded({ extended: true }));
// 首页路由
app.get('/', (req, res) => {
res.render('index');
});
// 启动服务器
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
2 创建视图
在项目根目录下创建 views 文件夹,并新建 index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">Node.js 网站</title>
</head>
<body>
<h1>欢迎来到 Node.js 网站!</h1>
</body>
</html>
运行 node app.js,访问 http://localhost:3000,你将看到首页内容。
数据库集成(MongoDB)
1 连接 MongoDB
在 app.js 中添加数据库连接代码:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/node-website', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB 连接成功'))
.catch(err => console.error('MongoDB 连接失败', err));
2 定义数据模型
创建 models/User.js:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: String,
email: String,
password: String
});
module.exports = mongoose.model('User', userSchema);
实现用户注册与登录
1 创建注册页面
在 views 文件夹下创建 register.ejs:
<form action="/register" method="POST">
<input type="text" name="username" placeholder="用户名" required>
<input type="email" name="email" placeholder="邮箱" required>
<input type="password" name="password" placeholder="密码" required>
<button type="submit">注册</button>
</form>
2 处理注册请求
在 app.js 中添加路由:
const User = require('./models/User');
app.post('/register', async (req, res) => {
try {
const { username, email, password } = req.body;
const user = new User({ username, email, password });
await user.save();
res.redirect('/login');
} catch (err) {
res.status(500).send('注册失败');
}
});
3 实现登录功能
类似地,创建 login.ejs 并添加登录逻辑:
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email, password });
if (user) {
res.redirect('/dashboard');
} else {
res.status(401).send('登录失败');
}
});
构建 RESTful API
1 创建 API 路由
在 app.js 中新增 API 路由:
app.get('/api/users', async (req, res) => {
const users = await User.find();
res.json(users);
});
app.post('/api/users', async (req, res) => {
const user = new User(req.body);
await user.save();
res.status(201).json(user);
});
2 测试 API
可以使用 Postman 或 curl 测试 API:
curl -X POST http://localhost:3000/api/users -H "Content-Type: application/json" -d '{"username":"test","email":"test@example.com","password":"123456"}'
部署到生产环境
1 使用 PM2 管理进程
安装 PM2:
npm install pm2 -g
启动应用:
pm2 start app.js
2 部署到云服务器
推荐使用 DigitalOcean、AWS 或 Heroku:
# 示例:Heroku 部署 heroku login heroku create git push heroku main
本文通过实战演示了如何使用 Node.js 开发一个完整的网站,包括:
- 搭建 Express 服务器
- 集成 MongoDB 数据库
- 实现用户认证
- 构建 RESTful API
- 部署到生产环境
Node.js 生态丰富,结合前端框架(如 React/Vue)可以构建更复杂的应用,希望这篇教程能帮助你快速上手 Node.js 网站开发!
(全文约 1500 字)