标签:users 包含 nsf 自动 图片 tran 传递 输出 str
参考https://www.runoob.com/nodejs/nodejs-restful-api.html
REST基本架构的四个方法:
首先,创建一个JSON格式的数据资源文件users.json:
{
"user1":{
"name": "mahesh",
"password":"password1",
"profession":"teacher",
"id":1
},
"user2":{
"name": "suresh",
"password":"password2",
"profession":"librarian",
"id":2
},
"user3":{
"name": "ramesh",
"password":"password3",
"profession":"clerk",
"id":3
}
}
基于此JSON格式,我们创建以下RESTful API:
在当前目录新建server.js文件:
var express = require(‘express‘);
var app = express();
var fs = require(‘fs‘);
app.get(‘/listUsers‘, (req, res)=>{
fs.readFile(__dirname+‘/users.json‘, ‘utf8‘, (err, data)=>{
console.log(data);
res.end(data);
});
});
var server = app.listen(8081, ()=>{
var host = server.address().address;
var port = server.address().port;
console.log("实例访问,地址为http://%s:%s", host, port);
});
结果:
控制台输出同样如此。
修改server.js文件,添加以下代码:
// 新的用户的数据
var user = {
"user4":{
"name":"mohit",
"password":"password4",
"id":4
}
};
app.get(‘/addUser‘, (req, res)=>{
fs.readFile(__dirname+‘/users.json‘, ‘utf8‘, (err, data)=>{
data = JSON.parse(data);
data[‘user4‘] = user[‘user4‘];
console.log(data);
res.end(JSON.stringify(data));
});
});
结果:
控制台输出:
{
user1: {
name: ‘mahesh‘,
password: ‘password1‘,
profession: ‘teacher‘,
id: 1
},
user2: {
name: ‘suresh‘,
password: ‘password2‘,
profession: ‘librarian‘,
id: 2
},
user3: { name: ‘ramesh‘, password: ‘password3‘, profession: ‘clerk‘, id: 3 },
user4: { name: ‘mohit‘, password: ‘password4‘, id: 4 }
}
server.js添加以下代码:
app.get(‘/:id‘, (req, res)=>{
fs.readFile(__dirname+‘/users.json‘, ‘utf8‘, (err, data)=>{
data = JSON.parse(data);
var my_user = data["user"+req.params.id];
console.log(my_user);
res.end(JSON.stringify(my_user));
});
});
结果:
控制台输出:
{ name: ‘mahesh‘, password: ‘password1‘, profession: ‘teacher‘, id: 1 }
var express = require(‘express‘);
var app = express();
var fs = require(‘fs‘);
var id=2;
app.get(‘/deleteUser‘, (req, res)=>{
fs.readFile(__dirname+‘/users.json‘, ‘utf8‘, (err, data)=>{
data = JSON.parse(data);
delete data[‘user‘+id];
console.log(data);
res.end(JSON.stringify(data));
});
});
var server = app.listen(8081, ()=>{
var host = server.address().address;
var port = server.address().port;
console.log("实例访问,地址为http://%s:%s", host, port);
});
结果:
控制台输出:
{
user1: {
name: ‘mahesh‘,
password: ‘password1‘,
profession: ‘teacher‘,
id: 1
},
user3: { name: ‘ramesh‘, password: ‘password3‘, profession: ‘clerk‘, id: 3 }
}
不知道为什么,最后的删除用户部分的代码和前几个部分的代码放在一起的时候,需要调整代码片段的顺序,后面几个片段始终会失效,分开写就没事了。
标签:users 包含 nsf 自动 图片 tran 传递 输出 str
原文地址:https://www.cnblogs.com/pangqianjin/p/14210041.html