在 Debian 上使用 Node.js 进行 API 开发
一 环境准备与 Node.js 安装
- 更新系统并安装基础工具:
- sudo apt update && sudo apt upgrade -y
- 安装 Node.js 与 npm(两种常用方式,择一即可):
- 使用系统仓库:sudo apt install -y nodejs npm
- 使用 NodeSource 仓库安装更新版本(示例为 16.x,可按需替换为其他版本):
- curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
- sudo apt-get install -y nodejs
- 验证安装:
- 建议:如需在同一台机器管理多个 Node.js 版本,可使用 NVM(Node Version Manager)安装与切换版本。
二 初始化项目与编写第一个 API
- 创建项目并初始化:
- mkdir my-api && cd my-api
- npm init -y
- 安装常用依赖(REST API 常用组合):
- npm install express body-parser cors
- 创建入口文件(如 server.js)并实现一个最小可用 API:
- const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const cors = require(‘cors’);
const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.use(bodyParser.json());
app.get(‘/api/hello’, (req, res) => {
res.json({ message: ‘Hello, World!’ });
});
app.listen(port, () => {
console.log(
Server is running on port ${port});
});
- 启动与测试:
- 生产启动脚本(在 package.json 中):
- “scripts”: { “start”: “node server.js” }
- 使用:npm start
三 进程守护与反向代理
- 使用 PM2 进行进程守护与开机自启:
- 安装:sudo npm install -g pm2
- 启动:pm2 start server.js --name my-api
- 常用:pm2 status、pm2 logs my-api、pm2 monit
- 设置开机自启:pm2 startup(按提示执行)
- 使用 Nginx 作为反向代理(提升性能与安全):
- 安装:sudo apt install nginx -y
- 配置站点(/etc/nginx/sites-available/my-api):
- server {
listen 80;
server_name your_domain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection ‘upgrade’;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
- 启用站点与生效:
- sudo ln -s /etc/nginx/sites-available/my-api /etc/nginx/sites-enabled
- sudo nginx -t && sudo systemctl restart nginx
- 防火墙放行(如使用 UFW):
- sudo ufw allow ‘Nginx Full’
四 进阶实践与常用工具
- 使用 NestJS 与 Swagger 搭建规范化的 API 与文档:
- 全局安装 CLI:sudo npm install -g @nestjs/cli
- 创建项目:nest new my-project && cd my-project
- 安装文档依赖:npm install @nestjs/swagger swagger-ui-express
- 在 src/main.ts 中配置 Swagger(示例):
- import { NestFactory } from ‘@nestjs/core’;
import { SwaggerModule, DocumentBuilder } from ‘@nestjs/swagger’;
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const options = new DocumentBuilder()
.setTitle(‘My Project’)
.setDescription(‘API description’)
.setVersion(‘1.0’)
.addTag(‘test’)
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup(‘api-doc’, app, document);
await app.listen(3000);
}
bootstrap();
- 启动开发服务:npm run start:dev
- 访问文档: http://localhost:3000/api-doc/#/
- 提示:Swagger UI 建议增加鉴权或仅在开发环境启用,避免未授权访问。