爱学习的小伙伴们,Node.js 服务器有听说过没,是否觉得陌生?如此,就一起动手搭建一个吧。会的小伙伴可以略过哟~
以下是搭建 Node.js 服务器的详细步骤:
1. 安装 Node.js 和 npm
- 下载安装:访问 Node.js 官网(https://nodejs.org/zh-cn),下载并安装 LTS 版本(包含 npm)。
- 验证安装:
node -v # 查看 Node.js 版本
npm -v # 查看 npm 版本
2. 初始化项目
- 创建项目文件夹并进入:
mkdir my-server && cd my-server
- 初始化 package.json:
npm init -y # -y 跳过提问,使用默认配置
3. 安装 Express(可选但推荐)
Express 是流行的 Node.js Web 框架。
npm install express --save
4. 创建服务器文件
新建 server.js,编写基础服务器代码:
// 导入 Express
const express = require('express');
const app = express();
const port = 3000; // 端口号
// 处理根路径 GET 请求
app.get('/', (req, res) => {
res.send('Hello World!');
});
// 启动服务器
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
5. 运行服务器
node server.js
访问 http://localhost:3000 查看效果。
6. 添加静态文件服务
托管 HTML、CSS、JS 等文件:
app.use(express.static('public')); // 将 public 文件夹设为静态目录
- 创建 public 文件夹,放入 index.html 等文件。
7. 处理其他路由和方法
示例:处理 POST 请求并解析 JSON 数据:
app.use(express.json()); // 解析 JSON 请求体
app.post('/api/data', (req, res) => {
const data = req.body;
res.json({ received: data });
});
8. 中间件使用
添加日志中间件:
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // 继续处理请求
});
9. 错误处理
自定义错误中间件:
// 404 处理
app.use((req, res) => {
res.status(404).send('Page not found');
});
// 全局错误处理
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Server error!');
});
10. 部署与生产环境
- 进程管理:使用 pm2 保持服务运行:
npm install pm2 -g
pm2 start server.js --name "my-server"
- 反向代理:通过 Nginx/Apache 转发请求。
- 环境变量:使用 dotenv 管理敏感配置:
npm install dotenv --save
创建 .env 文件:
PORT=3000
在代码中读取:
require('dotenv').config();
const port = process.env.PORT;
11. 扩展功能
- 数据库连接:集成 MongoDB(使用 mongoose)或 MySQL。
- 用户认证:使用 passport 或 jsonwebtoken。
- 模板引擎:如 ejs、pug 渲染动态页面。
12.完整示例代码
const express = require('express');
const app = express();
require('dotenv').config();
// 中间件
app.use(express.json());
app.use(express.static('public'));
// 路由
app.get('/', (req, res) => {
res.send('Home Page');
});
app.post('/api/submit', (req, res) => {
res.json({ status: 'success', data: req.body });
});
// 错误处理
app.use((req, res) => {
res.status(404).send('404 Not Found');
});
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
通过以上步骤,你可以快速搭建一个功能完备的 Node.js 服务器,并根据需求扩展功能。
好了,爱学习的小伙伴,更多精彩,关注不迷路哟~
node.js