Node.js RESTful API
2021-01-04 17:27
标签:users 包含 nsf 自动 图片 tran 传递 输出 str 参考https://www.runoob.com/nodejs/nodejs-restful-api.html REST基本架构的四个方法: 首先,创建一个JSON格式的数据资源文件users.json: 基于此JSON格式,我们创建以下RESTful API: 在当前目录新建server.js文件: 结果: 修改server.js文件,添加以下代码: 结果: server.js添加以下代码: 结果: 结果: 不知道为什么,最后的删除用户部分的代码和前几个部分的代码放在一起的时候,需要调整代码片段的顺序,后面几个片段始终会失效,分开写就没事了。 Node.js RESTful API 标签:users 包含 nsf 自动 图片 tran 传递 输出 str 原文地址:https://www.cnblogs.com/pangqianjin/p/14210041.htmlNode.js RESTful API
什么是REST?
HTTP方法
RESTful Web Services
创建RESTful
{
"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
}
}
获取用户列表
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);
});
控制台输出同样如此。添加用户
// 新的用户的数据
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 }
}
显示用户详情
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 }
}
文章标题:Node.js RESTful API
文章链接:http://soscw.com/index.php/essay/40080.html