如何用Node.js编写一个简单的增删改查接口示例代码?

更新于
2026-10-01 10:12:00
1阅读来源:SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计619个文字,预计阅读时间需要3分钟。

如何用Node.js编写一个简单的增删改查接口示例代码?

javascript// 使用Node.js实现简单的增删改查接口const express=require('express');const fs=require('fs');const cors=require('cors');const bodyParser=require('body-parser');

const app=express();

app.use(cors());app.use(bodyParser.json());

// 读取文件function readFile(filename) { return new Promise((resolve, reject)=> { fs.readFile(filename, 'utf8', (err, data)=> { if (err) reject(err); resolve(data); }); });}

// 写入文件function writeFile(filename, data) { return new Promise((resolve, reject)=> { fs.writeFile(filename, data, 'utf8', (err)=> { if (err) reject(err); resolve(); }); });}

// 获取所有用户app.get('/users', async (req, res)=> { try { const data=await readFile('users.json'); res.json(JSON.parse(data)); } catch (err) { res.status(500).send(err); }});

// 添加用户app.post('/users', async (req, res)=> { try { const users=await readFile('users.json'); const newUser={ id: Date.now(), ...req.body }; const updatedUsers=[...JSON.parse(users), newUser]; await writeFile('users.json', JSON.stringify(updatedUsers)); res.status(201).json(newUser); } catch (err) { res.status(500).send(err); }});

// 更新用户app.put('/users/:id', async (req, res)=> { try { const users=await readFile('users.json'); const { id }=req.params; const index=JSON.parse(users).findIndex(user=> user.id===parseInt(id)); if (index===-1) { return res.status(404).send('User not found'); } const updatedUsers=JSON.parse(users).map(user=> user.id===parseInt(id) ? { ...user, ...req.body } : user); await writeFile('users.json', JSON.stringify(updatedUsers)); res.json(updatedUsers[index]); } catch (err) { res.status(500).send(err); }});

// 删除用户app.delete('/users/:id', async (req, res)=> { try { const users=await readFile('users.json'); const { id }=req.params; const updatedUsers=JSON.parse(users).filter(user=> user.id !==parseInt(id)); await writeFile('users.json', JSON.stringify(updatedUsers)); res.status(204).send(); } catch (err) { res.status(500).send(err); }});

const PORT=process.env.PORT || 3000;app.listen(PORT, ()=> { console.log(`Server is running on port ${PORT}`);});

node实现简单的增删改查接口的全部代码如下:

// 数据存储在users.json文件中 const express = require("express"); const fs = require("fs"); const cors = require("cors"); const bodyParser = require("body-parser"); const app = express(); app.use(cors({ origin: "*" })); // fix 跨域 app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded // 新增 app.post("/addUser", (req, res) => { fs.readFile("./users.json", "utf8", (err, data) => { if (err) { throw err; } data = data ? JSON.parse(data) : []; data.push(req.body); fs.writeFile("./users.json", JSON.stringify(data), err => { if (err) throw err; res.end(); }); }); }); // 删除 app.delete("/delUser/:id", (req, res) => { const id = req.params.id; fs.readFile("./users.json", "utf8", (err, data) => { data = JSON.parse(data) || []; const saveData = data.filter(item => item.id != id); fs.writeFile("./users.json", JSON.stringify(saveData), err => { if (err) throw err; res.end(); }); }); }); // 修改 app.put("/update/:id", (req, res) => { const id = req.params.id; const body = req.body; fs.readFile(__dirname + "/" + "users.json", "utf8", (err, data) => { const userList = (data && JSON.parse(data)) || []; const index = userList.findIndex(item => item.id == id); userList[index] = { ...userList[index], ...body }; fs.writeFile("./users.json", JSON.stringify(userList), err => { if (err) throw err; console.log("修改"); res.end(); }); }); }); // 列表查询 app.get("/listUsers", function(req, res) { fs.readFile(__dirname + "/" + "users.json", "utf8", function(err, data) { console.log(data); res.end(data); }); }); app.listen(8081, function() { console.log("访问地址: localhost:8081"); });

以上就是全部相关代码,大家可以测试下,感谢大家对易盾网络的支持。

如何用Node.js编写一个简单的增删改查接口示例代码?

本文共计619个文字,预计阅读时间需要3分钟。

如何用Node.js编写一个简单的增删改查接口示例代码?

javascript// 使用Node.js实现简单的增删改查接口const express=require('express');const fs=require('fs');const cors=require('cors');const bodyParser=require('body-parser');

const app=express();

app.use(cors());app.use(bodyParser.json());

// 读取文件function readFile(filename) { return new Promise((resolve, reject)=> { fs.readFile(filename, 'utf8', (err, data)=> { if (err) reject(err); resolve(data); }); });}

// 写入文件function writeFile(filename, data) { return new Promise((resolve, reject)=> { fs.writeFile(filename, data, 'utf8', (err)=> { if (err) reject(err); resolve(); }); });}

// 获取所有用户app.get('/users', async (req, res)=> { try { const data=await readFile('users.json'); res.json(JSON.parse(data)); } catch (err) { res.status(500).send(err); }});

// 添加用户app.post('/users', async (req, res)=> { try { const users=await readFile('users.json'); const newUser={ id: Date.now(), ...req.body }; const updatedUsers=[...JSON.parse(users), newUser]; await writeFile('users.json', JSON.stringify(updatedUsers)); res.status(201).json(newUser); } catch (err) { res.status(500).send(err); }});

// 更新用户app.put('/users/:id', async (req, res)=> { try { const users=await readFile('users.json'); const { id }=req.params; const index=JSON.parse(users).findIndex(user=> user.id===parseInt(id)); if (index===-1) { return res.status(404).send('User not found'); } const updatedUsers=JSON.parse(users).map(user=> user.id===parseInt(id) ? { ...user, ...req.body } : user); await writeFile('users.json', JSON.stringify(updatedUsers)); res.json(updatedUsers[index]); } catch (err) { res.status(500).send(err); }});

// 删除用户app.delete('/users/:id', async (req, res)=> { try { const users=await readFile('users.json'); const { id }=req.params; const updatedUsers=JSON.parse(users).filter(user=> user.id !==parseInt(id)); await writeFile('users.json', JSON.stringify(updatedUsers)); res.status(204).send(); } catch (err) { res.status(500).send(err); }});

const PORT=process.env.PORT || 3000;app.listen(PORT, ()=> { console.log(`Server is running on port ${PORT}`);});

node实现简单的增删改查接口的全部代码如下:

// 数据存储在users.json文件中 const express = require("express"); const fs = require("fs"); const cors = require("cors"); const bodyParser = require("body-parser"); const app = express(); app.use(cors({ origin: "*" })); // fix 跨域 app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded // 新增 app.post("/addUser", (req, res) => { fs.readFile("./users.json", "utf8", (err, data) => { if (err) { throw err; } data = data ? JSON.parse(data) : []; data.push(req.body); fs.writeFile("./users.json", JSON.stringify(data), err => { if (err) throw err; res.end(); }); }); }); // 删除 app.delete("/delUser/:id", (req, res) => { const id = req.params.id; fs.readFile("./users.json", "utf8", (err, data) => { data = JSON.parse(data) || []; const saveData = data.filter(item => item.id != id); fs.writeFile("./users.json", JSON.stringify(saveData), err => { if (err) throw err; res.end(); }); }); }); // 修改 app.put("/update/:id", (req, res) => { const id = req.params.id; const body = req.body; fs.readFile(__dirname + "/" + "users.json", "utf8", (err, data) => { const userList = (data && JSON.parse(data)) || []; const index = userList.findIndex(item => item.id == id); userList[index] = { ...userList[index], ...body }; fs.writeFile("./users.json", JSON.stringify(userList), err => { if (err) throw err; console.log("修改"); res.end(); }); }); }); // 列表查询 app.get("/listUsers", function(req, res) { fs.readFile(__dirname + "/" + "users.json", "utf8", function(err, data) { console.log(data); res.end(data); }); }); app.listen(8081, function() { console.log("访问地址: localhost:8081"); });

以上就是全部相关代码,大家可以测试下,感谢大家对易盾网络的支持。

如何用Node.js编写一个简单的增删改查接口示例代码?