当前位置:网站首页>koa2对Json数组增删改查
koa2对Json数组增删改查
2022-07-06 15:41:00 【~疆】
参考:
nodejs框架如何对json文件进行增删改查 - web开发 - 亿速云这篇文章主要为大家展示了“nodejs框架如何对json文件进行增删改查”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习�...https://www.yisu.com/zixun/168616.html小案例:javascript实现对json文件的增删改查_奄奄一息的一条咸鱼的博客-CSDN博客_js对json增删改查下面为books.json格文件的数据[{ "id": 1, "bookName": "完美世界", "author": "辰东", "hero": "石昊"}, { "id": 2, "bookName": "武庚纪", "author": "沈乐平", "hero": "武庚"}, { "id": 4, "bookName": "天行九歌", "author": "陈岚", "hero": "韩非"}https://blog.csdn.net/weixin_46682277/article/details/123011417
前端
index.vue:
<!--page1-->
<template>
<div class="userManage">
<el-card>
<div style="margin-bottom: 10px">
<el-input
v-model="searchName"
clearable
placeholder="输入用户名称搜索"
style="width: 200px; margin-right: 10px"
/>
<el-button
sizi="mini"
type="success"
icon="el-icon-search"
@click="searchUser(searchName)"
>搜索</el-button
>
<el-button
sizi="mini"
type="warning"
icon="el-icon-refresh-left"
@click="searchName = ''"
>重置</el-button
>
<el-button
sizi="mini"
@click="handleAdd()"
type="primary"
icon="el-icon-plus"
>新增</el-button
>
<el-button
@click="getUserList()"
sizi="mini"
icon="el-icon-refresh"
style="float: right"
>刷新</el-button
>
</div>
<el-table :data="tableData" border v-loading="isLoading">
<el-table-column type="selection" width="55"> </el-table-column>
<el-table-column
label="用户名"
prop="username"
align="center"
width="150px"
></el-table-column>
<el-table-column
label="密码"
prop="password"
align="center"
></el-table-column>
<el-table-column label="操作" align="center">
<template slot-scope="scope">
<el-button size="mini" @click="showEditDialog(scope.row)">
<i class="el-icon-edit" /> 编辑
</el-button>
<el-button
size="mini"
type="danger"
@click="handleDelete(scope.row)"
>
<i class="el-icon-delete" /> 删除
</el-button>
</template>
</el-table-column>
</el-table>
</el-card>
<UserManageDialog
:dialog="dialog"
:formData="formData"
@addUser="addUser"
@editUser="editUser"
></UserManageDialog>
</div>
</template>
<script>
import axios from "axios";
import UserManageDialog from "./userManageDialog.vue";
import qs from "qs";
export default {
name: "page1",
components: { UserManageDialog },
data() {
return {
searchName: "",
isLoading: false,
dialog: {
show: false,
title: "",
},
formData: {
id: "",
username: "",
password: "",
},
tableData: [
{
id: "",
username: "admin",
password: "123",
},
],
};
},
props: {},
created() {},
mounted() {
this.getUserList();
},
computed: {},
methods: {
//打开新增用户窗口
handleAdd() {
this.dialog = {
show: true,
title: "新增用户",
option: "add",
};
this.formData = {
username: "",
password: "",
};
},
//打开编辑用户窗口
showEditDialog(row) {
console.log("row:", row);
this.dialog = {
show: true,
title: "编辑用户",
option: "edit",
};
this.formData = {
id: row.id,
username: row.username,
password: row.password,
};
},
//获取用户列表
async getUserList() {
this.isLoading = true;
let data = await axios.get("http://localhost:3000/users");
this.tableData = data.data.data.users;
this.isLoading = false;
},
//根据用户名查询
async searchUser(searchName) {
if (!searchName) {
this.getUserList();
return;
}
this.isLoading = true;
let { data } = await axios.get(
"http://localhost:3000/users/findByUsername",
{
params: { username: searchName },
}
);
this.tableData = data.data;
this.isLoading = false;
},
//删除用户
handleDelete(row) {
this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(async () => {
await axios.delete(`http://localhost:3000/users`, {
params: { id: row.id },
});
this.$message({
type: "success",
message: "删除成功!",
showClose: true,
});
this.getUserList();
})
.catch(() => {
this.$message({
type: "info",
message: "已取消删除",
showClose: true,
});
});
},
//新增用户
async addUser() {
await axios.post(
"http://localhost:3000/users",
qs.stringify({
username: this.formData.username,
password: this.formData.password,
})
);
this.dialog.show = false;
this.$notify({
title: "成功",
message: "新增用户成功!",
type: "success",
});
this.getUserList();
},
//编辑用户
async editUser() {
await axios.put("http://localhost:3000/users", {
id: this.formData.id,
username: this.formData.username,
password: this.formData.password,
});
this.dialog.show = false;
this.$notify({
title: "成功",
message: "编辑用户成功!",
type: "success",
});
this.getUserList();
},
},
watch: {},
};
</script>
userManageDialog.vue:
<!--userManageDialog -->
<template>
<div class="userManageDialog">
<el-dialog
:title="dialog.title"
width="45%"
:visible.sync="dialog.show"
v-if="dialog.show"
>
<el-form
ref="ref_form_userManage"
:model="formData"
:rules="rules"
label-width="100px"
>
<el-form-item label="用户名" prop="username">
<el-input
v-model="formData.username"
autocomplete="off"
style="width: 90%"
></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input
v-model="formData.password"
autocomplete="off"
style="width: 90%"
></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialog.show = false">取 消</el-button>
<el-button
v-if="dialog.option == 'add'"
@click="addUser('ref_form_userManage')"
type="primary"
>确 定</el-button
>
<el-button
v-if="dialog.option == 'edit'"
@click="editUser('ref_form_userManage')"
type="primary"
>确 定</el-button
>
</div>
</el-dialog>
</div>
</template>
<script>
export default {
name: "userManageDialog",
props: ["dialog", "formData"],
data() {
return {
fileList: [],
rules: {
username: [
{ required: true, message: "请输入用户名称", trigger: "blur" },
],
},
};
},
created() {},
mounted() {},
computed: {},
methods: {
addUser(formName) {
this.$refs[formName].validate(async (valid) => {
if (valid) {
this.$emit("addUser");
} else {
console.log("error submit!!");
return false;
}
});
},
editUser(formName) {
this.$refs[formName].validate(async (valid) => {
if (valid) {
this.$emit("editUser");
} else {
console.log("error submit!!");
return false;
}
});
},
},
watch: {},
};
</script>
<style lang="scss" scoped>
</style>
后端:
users.js:
const router = require('koa-router')()
const fs = require("fs")
const uuid = require('uuid');
router.prefix('/users')
//根据username查询用户
router.get('/findByUsername', async (ctx, next) => {
let { username } = ctx.request.query
let findJson = () => {
return new Promise((resolve, reject) => {
fs.readFile('users.json', 'utf-8', function (err, data) {
if (err) {
resolve({ code: -1, msg: '查询失败' + err })
return console.error(err);
}
resolve({ code: 0, data: JSON.parse(data).users.filter((item) => item.username === username) })
})
})
}
ctx.body = await findJson()
})
//查询所有用户
router.get('/', async (ctx, next) => {
let findJson = () => {
return new Promise((resolve, reject) => {
fs.readFile('users.json', 'utf-8', function (err, data) {
if (err) {
resolve({ code: -1, msg: '查询失败' + err })
return console.error(err);
}
resolve({ code: 0, data: JSON.parse(data) })
})
})
}
ctx.body = await findJson()
})
//删除用户
router.delete('/', async (ctx, next) => {
let { id } = ctx.request.query;
let deleteJson = () => {
return new Promise((resolve, reject) => {
fs.readFile('users.json', 'utf-8', function (err, data) {
if (err) {
resolve({ code: -1, msg: '删除失败' + err })
return console.error(err);
}
let jsonData = JSON.parse(data).users.filter((item) => item.id !== id);
fs.writeFile('users.json', JSON.stringify({ "users": jsonData }), function (err) {
if (err) {
resolve({ code: -1, msg: '删除失败' + err })
}
resolve({ code: 0, msg: '删除成功' })
})
})
})
}
ctx.body = await deleteJson()
})
//添加用户
router.post('/', async (ctx, next) => {
let { username, password } = ctx.request.body
let id = uuid.v4();
let writeJson = () => {
return new Promise((resolve, reject) => {
fs.readFile('users.json', 'utf-8', function (err, data) {
if (err) {
resolve({ code: -1, msg: '新增失败' + err })
return console.error(err);
}
let jsonData = JSON.parse(data)
jsonData.users.push({ id, username, password })
fs.writeFile('users.json', JSON.stringify(jsonData), function (err) {
if (err) {
resolve({ code: -1, msg: '新增失败' + err })
}
resolve({ code: 0, msg: '新增成功' })
})
})
})
}
// 返回给前端
ctx.body = await writeJson()
})
//修改用户
router.put('/', async (ctx, next) => {
let { id, username, password } = ctx.request.body
let writeJson = () => {
return new Promise((resolve, reject) => {
fs.readFile('users.json', 'utf-8', function (err, data) {
if (err) {
resolve({ code: -1, msg: '修改失败' + err })
return console.error(err);
}
let jsonData = JSON.parse(data).users
jsonData.splice(jsonData.findIndex(item => item.id === id), 1, { id, username, password })
fs.writeFile('users.json', JSON.stringify({ "users": jsonData }), function (err) {
if (err) {
resolve({ code: -1, msg: '修改失败' + err })
}
resolve({ code: 0, msg: '修改成功' })
})
})
})
}
// 返回给前端
ctx.body = await writeJson()
})
module.exports = router
users.json:
{
"users": [
{
"id": "adfsg",
"username": "李四",
"password": "444asd"
},
{
"id": "d4d2c1df-8c78-4cba-9e42-58c83c26eb5b",
"username": "ag",
"password": "dfg"
},
{
"id": "cadbd3d6-6cab-4f82-ae2d-fe2c0ceae5b7",
"username": "tasdfasd",
"password": "rtasdf"
}
]
}
边栏推荐
- mysql查看表结构的三种方法总结
- 企業不想換掉用了十年的老系統
- Financial professionals must read book series 6: equity investment (based on the outline and framework of the CFA exam)
- Method of canceling automatic watermarking of uploaded pictures by CSDN
- Mysql 身份认证绕过漏洞(CVE-2012-2122)
- docker中mysql开启日志的实现步骤
- POJ 1258 Agri-Net
- 第十九章 使用工作队列管理器(二)
- The statement that allows full table scanning does not seem to take effect set odps sql. allow. fullscan=true; I
- OpenNMS separation database
猜你喜欢
Pdf batch splitting, merging, bookmark extraction, bookmark writing gadget
B站大佬用我的世界搞出卷积神经网络,LeCun转发!爆肝6个月,播放破百万
The problem that dockermysql cannot be accessed by the host machine is solved
Custom swap function
PDF批量拆分、合并、书签提取、书签写入小工具
Unified Focal loss: Generalising Dice and cross entropy-based losses to handle class imbalanced medi
With the help of this treasure artifact, I became the whole stack
GPT-3当一作自己研究自己,已投稿,在线蹲一个同行评议
ICLR 2022 | 基于对抗自注意力机制的预训练语言模型
DR-Net: dual-rotation network with feature map enhancement for medical image segmentation
随机推荐
Custom swap function
Dockermysql modifies the root account password and grants permissions
Method of canceling automatic watermarking of uploaded pictures by CSDN
Docker mysql5.7 how to set case insensitive
让 Rust 库更优美的几个建议!你学会了吗?
Les entreprises ne veulent pas remplacer un système vieux de dix ans
Use ECs to set up an agent
dockermysql修改root账号密码并赋予权限
DR-Net: dual-rotation network with feature map enhancement for medical image segmentation
Let's see through the network i/o model from beginning to end
Two week selection of tdengine community issues | phase II
Slide the uniapp to a certain height and fix an element to the top effect demo (organize)
QT signal and slot
Modules that can be used by both the electron main process and the rendering process
食品里的添加剂品种越多,越不安全吗?
(flutter2) as import old project error: inheritfromwidgetofexacttype
OpenSSL:适用TLS与SSL协议的全功能工具包,通用加密库
Motion capture for snake motion analysis and snake robot development
The application of machine learning in software testing
(DART) usage supplement