Node.js Express RESTful 简单例子

本文通过一个简单的例子展示如何使用Node.js和Express框架创建RESTful API,涉及数据查询和删除功能。示例中,数据源采用json文件data.json,并提供了查询所有、查询单个、新增和删除操作的实现。利用Postman工具进行接口测试。

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测试

查询所有

查询单个

新增

删除

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值