使用Express框架在服务端创建API

导读

本文详细介绍了如何通过Node.jsnpm快速创建接口服务器,实现前后端分离架构下的数据交互与服务支撑。

1.环境准备

Ubuntu系统为例,确保服务器端已经安装了Node.js和npm。

1.1. 安裝Node.js和npm

1
2
3
4
5
# 更新软件包列表
sudo apt update

# 安装 Node.js 和 npm
sudo apt install nodejs npm -y

1.2. 查看安装版本(验证)

在终端运行以下命令检查是否已安装:

1
2
nodejs --version    # 显示 Node.js 版本
npm --version # 显示 npm 版本

2.初始化项目

创建项目文件夹(如果通过1panel创建的站点,进入到该站点index下即可),并在该项目目录下运行:

1
npm init -y   # 初始化项目

3.安装Express

在项目目录下运行:

1
npm install express  # 安装Express 

4.添加代码

在项目目录下创建一个名为index.js的文件,并添加以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const express = require('express');  // 引入 Express 模块,用于创建 Web 服务器
const app = express(); // 创建一个 Express 应用实例
const port = 3000; // 定义服务器监听的端口号

// 中间件,用于解析JSON请求体
app.use(express.json());

// 定义一个简单的GET路由
app.get('/', (req, res) => {
res.send('Hello World!');
});

// 定义一个简单的POST路由
app.post('/data', (req, res) => {
const data = req.body;
res.send(`You sent: ${JSON.stringify(data)}`);
});

// 启动服务器,监听指定端口
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

注意:以上配置中定义了端口号,记得在防火墙放行,放行端口运行:

1
ufw allow <port>  # Ubuntu放行指令

配置进阶操作

(1)引入数据库服务
PostgreSQL客户端(包含连接池功能)为例:
① 安装 pg cors express,在项目目录下运行:

1
npm install pg cors express    # 安装数据库依赖

② 修改代码加载环境变量,在index.js文件里面加入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const { Pool } = require('pg');  // 引入 pg 模块,并从中解构出 Pool 类

// 创建 PostgreSQL 连接池实例(所有参数直接写死)
const pool = new Pool({
user: 'your_db_user', // 替换为你的数据库用户名
host: 'your_db_host', // 替换为数据库地址(如 localhost)
database: 'your_db_name', // 替换为数据库名
password: 'your_db_password', // 替换为数据库密码
port: 5432, // PostgreSQL 默认端口
max: 20, // 连接池最大连接数
idleTimeoutMillis: 30000, // 连接空闲超时时间(毫秒)
connectionTimeoutMillis: 2000 // 连接超时时间(毫秒)
});

// 测试数据库连接(可选)
pool.query('SELECT NOW()', (err, res) => {
if (err) {
console.error('数据库连接失败或查询失败:', err.stack);
} else {
console.log('数据库连接成功,当前时间:', res.rows[0].now);
}
});

// 导出 pool 实例,方便其他模块使用
module.exports = pool;

④ 重启应用,验证是否成功生效。
(2)CORS 配置​(跨域)
① 安装 cors,在项目目录下运行:

1
npm install cors    # 安装 dotenv 管理环境变量

② 修改代码加载环境变量,在index.js文件里面加入以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const cors = require('cors');   // 引入 cors 模块,用于处理跨域请求

// CORS 配置
app.use(cors({
origin: function (origin, callback) {
const allowedOrigins = [
'https://xxxx.com',
'http://localhost:4000'
];
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
credentials: true,
optionsSuccessStatus: 204

④ 重启应用,验证是否成功生效。
(3)使用环境变量配置文件
① 安装 dotenv,在项目目录下运行:

1
npm install dotenv    # 安装 dotenv 管理环境变量

② 在项目目录下创建.env文件,并按照格式写入以下配置:

1
2
3
4
5
6
7
8
9
# 数据库配置
DB_USER=your_db_user // 替换为你的数据库用户名
DB_HOST=localhost // 替换为数据库地址(如 localhost)
DB_NAME=your_db_name // 替换为数据库名
DB_PASSWORD=your_db_password // 替换为数据库密码
DB_PORT=5432 // PostgreSQL 默认端口

# Express 监听端口
PORT=3000

③ 修改代码加载环境变量,在index.js文件里面加入以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
require('dotenv').config();      // 加载 dotenv 模块,用于读取 .env 文件中的环境变量(新增)
const { Pool } = require('pg'); // 引入 pg 模块,并从中解构出 Pool 类

// 创建数据库连接池实例
const pool = new Pool({
user: process.env.DB_USER, // 从环境变量中读取数据库用户
host: process.env.DB_HOST, // 数据库服务器地址(IP 或域名)
database: process.env.DB_NAME, // 要连接的数据库名称
password: process.env.DB_PASSWORD, // 数据库密码
port: parseInt(process.env.DB_PORT || 5432, 10), // 数据库端口号,默认为 5432(PostgreSQL 默认端口)
max: 20, // 连接池最大连接数
idleTimeoutMillis: 30000, // 空闲连接超时时间(毫秒),超过该时间未被使用则断开连接
connectionTimeoutMillis: 2000 // 建立新连接的超时时间(毫秒)
});

④ 重启应用,验证是否成功生效。

5. 启动服务

在项目目录下运行以下命令来启动服务器:

1
node index.js    # 启动服务

如果启动成功,你会看到Server is running on http://localhost:3001, 现在,你的API服务器应该在 http://localhost:3000 上运行。你可以通过浏览器访问该地址,或者使用工具(如Postman)来测试POST请求。如果通过1panel创建站点,绑定域名,这时就可直接使用域名访问,页面应该会返回Hello World!

使用pm2管理启动服务

6. 使用pm2管理启动服务

6.1.安装 pm2

使用 npm(Node.js 的包管理器)全局安装 pm2:

1
sudo npm install pm2@latest -g    # 全局安装pm2

6.2.验证安装

安装完成后,可以通过以下命令验证 PM2 是否安装成功,如果输出显示 PM2 的版本号,则表示 PM2 已成功安装。

1
pm2 -v   # 显示 pm2 版本

6.3.启动应用程序

使用 PM2 启动你的应用程序,例如 index.js:

1
pm2 start index.js   # 启动 index.js

如果启动时要指定应用程序名称,可通过以下命令操作:

1
pm2 start index.js --name "api-1"

6.4.查看应用程序状态

保存至pm2进程列表:

1
pm2 save      # 保存进程列表

6.5.设置开机自启

配置 PM2 在服务器重启时自动启动应用程序:

1
pm2 startup   # 设置开机自启

6.6. 常见pm2指令合集

(1)查看所有运行应用程序及其状态

1
pm2 list      # 查看所有运行应用

(2)修改现有运行中的进程名称​

1
2
3
pm2 restart index.js --name "index"  # 先停止并重新启动
#
pm2 reload index.js --name "index" # 无缝重载

(3)停止应用

1
2
pm2 stop <name|id>    # 停止某个应用(通过应用名称或ID)
pm2 stop all # 停止所有应用

(4)删除应用(停止并从列表中移除)

1
2
pm2 delete <name|id>  # 删除某个应用(通过应用名称或ID)
pm2 delete all # 删除所有应用

(4)强制终止所有 PM2 进程

1
pm2 kill   # 强制终止所有 PM2 进程

(5)查看服务器资源占用​

1
2
pm2 monit     # 实时监控  
htop # 查看整体 CPU/内存

(6)重启所有应用

1
pm2 restart all   # 重启所有应用