在Ubuntu上进行Node.js API开发,可按以下步骤操作:
安装Node.js和npm
sudo apt update
sudo apt install nodejs npm
验证安装:node -v
、npm -v
。curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install --lts
```。
初始化项目
mkdir my-api
cd my-api
npm init -y
```。
安装框架与依赖
npm install express
npm install body-parser cors
```。
编写API代码
app.js
文件,示例代码(以RESTful API为例):const express = require('express');
const app = express();
app.use(express.json()); // 解析JSON请求体
// 示例路由:获取所有用户
app.get('/api/users', (req, res) => {
res.json([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);
});
// 示例路由:创建用户
app.post('/api/users', (req, res) => {
const user = req.body;
res.status(201).json(user);
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
```。
运行与测试
node app.js
```。
http://localhost:3000/api/users
。curl -X POST -H "Content-Type: application/json" -d '{"name":"Charlie"}' http://localhost:3000/api/users
```。
进阶开发
参考资料:[1,2,3,4,5,6,7,8,9,10,11]