在Ubuntu中利用Node.js开发API可按以下步骤进行:
安装Node.js和npm
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install --lts
验证安装:node -v
和 npm -v
。
创建项目并初始化
mkdir my-api
cd my-api
npm init -y
安装Express框架
npm install express --save
编写API代码
创建server.js
文件,示例代码(含GET/POST接口):
const express = require('express');
const app = express();
const port = 3000;
// 解析JSON请求体
app.use(express.json());
// GET接口示例
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello, World!' });
});
// POST接口示例
app.post('/api/greet', (req, res) => {
const { name = 'Guest' } = req.body;
res.json({ message: `Hello, ${name}!` });
});
// 启动服务器
app.listen(port, () => {
console.log(`API running at http://localhost:${port}`);
});
运行和测试API
node server.js
http://localhost:3000/api/hello
curl
测试POST接口(如curl -X POST -H "Content-Type: application/json" -d '{"name":"Alice"}' http://localhost:3000/api/greet
)生产环境优化(可选)
pm2
管理进程:npm install pm2 -g
,然后pm2 start server.js
以上步骤基于Express框架快速搭建API,可根据需求扩展路由、中间件及功能模块。