Node.js Express RESTful 一个简单例子,实现对数据的查询和删除基本功能。
用一个json文件data.json作为读写的数据源
[ { "id": 1, "name": "aa" }, { "id": 2, "name": "bb" } ]
创建 RESTful
const express = require('express'); const app = express(); const fs = require("fs"); app.set('port', process.env.PORT || 3000); const jsonFile = __dirname + '/data.json'; //查询所有 app.get('/list', (req, res) => { fs.readFile(jsonFile, 'utf8', (err, data) => { console.log(data); res.end(data); }); }); //查询单个 app.get('/detail/:id', (req, res) => { fs.readFile(jsonFile, 'utf8', (err, data) => { data = JSON.parse(data); const d = data.filter(x => x.id == req.params.id); console.log(d); res.end(JSON.stringify(d)); }); }); const newData = { "id": 3, "name": "cc" }; //添加 app.post('/add', (req, res) => { fs.readFile(jsonFile, 'utf8', (err, data) => { data = JSON.parse(data); data.push(newData); console.log(data); saveJson(data); res.send(data); }); }); //删除 app.get('/delete/:id', (req, res) => { fs.readFile(jsonFile, 'utf8', (err, data) => { data = JSON.parse( data ); const index = data.findIndex(x => x.id == req.params.id); data.splice(index, 1); console.log(data); saveJson(data); res.send(data); }); }); //保存到文件 function saveJson(data){ fs.writeFile(jsonFile, JSON.stringify(data), "utf-8", err => { if (!err) { console.log('写入成功!') }else{ console.log('写入失败!') } }); } app.listen(app.get('port'), () => { console.log('Server listening on: http://localhost:', app.get('port')); });
Postman测试
查询所有
查询单个
新增
删除