使用Node.js构建RESTful API
安装Node.js和Express
首先,确保你已经安装了Node.js。然后使用npm安装Express框架:
创建Express应用
创建一个基本的Express应用:
1 2 3 4 5 6 7 8 9 10 11 12 13
| const express = require('express'); const app = express(); const port = 3000;
app.use(express.json());
app.get('/', (req, res) => { res.send('Hello World!'); });
app.listen(port, () => { console.log(`Server is running on port ${port}`); });
|
定义RESTful API路由
以下是一个简单的CRUD示例:
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 26 27 28 29 30 31 32 33
| let items = [];
app.post('/items', (req, res) => { const item = req.body; items.push(item); res.status(201).send(item); });
app.get('/items', (req, res) => { res.send(items); });
app.get('/items/:id', (req, res) => { const item = items.find(i => i.id === parseInt(req.params.id)); if (!item) return res.status(404).send('Item not found'); res.send(item); });
app.put('/items/:id', (req, res) => { const item = items.find(i => i.id === parseInt(req.params.id)); if (!item) return res.status(404).send('Item not found');
item.name = req.body.name; res.send(item); });
app.delete('/items/:id', (req, res) => { const itemIndex = items.findIndex(i => i.id === parseInt(req.params.id)); if (itemIndex === -1) return res.status(404).send('Item not found');
items.splice(itemIndex, 1); res.status(204).send(); });
|
总结
使用Node.js和Express构建RESTful API非常简单且高效,这使得它成为构建后端服务的流行选择。
思维导图
1 2 3 4
| graph TD; A[使用Node.js构建RESTful API] --> B[安装Node.js和Express] A --> C[创建Express应用] A --> D[定义RESTful API路由]
|