当前位置:网站首页>Koa2 addition, deletion, modification and query of JSON array
Koa2 addition, deletion, modification and query of JSON array
2022-07-06 23:14:00 【~Xinjiang】
Reference resources :
nodejs How to frame json Add, delete, modify and check the documents - web Development - Billion speed cloud This article mainly shows you “nodejs How to frame json Add, delete, modify and check the documents ”, The content is simple and easy to understand , Clarity of organization , I hope I can help you solve your doubts , Now let Xiaobian lead you to study and learn �...https://www.yisu.com/zixun/168616.html Small cases :javascript Realize to json Check the addition, deletion and modification of documents _ Blog of a dying salted fish -CSDN Blog _js Yes json Additions and deletions The following is books.json Grid file data [{ "id": 1, "bookName": " A perfect world ", "author": " Chendong ", "hero": " Shi Hao "}, { "id": 2, "bookName": " Wugeng period ", "author": " Shen Leping ", "hero": " Wu Geng "}, { "id": 4, "bookName": " Nine songs of heaven ", "author": " Chen Lan ", "hero": " Han Fei "}https://blog.csdn.net/weixin_46682277/article/details/123011417
front end
index.vue:
<!--page1-->
<template>
<div class="userManage">
<el-card>
<div style="margin-bottom: 10px">
<el-input
v-model="searchName"
clearable
placeholder=" Enter user name search "
style="width: 200px; margin-right: 10px"
/>
<el-button
sizi="mini"
type="success"
icon="el-icon-search"
@click="searchUser(searchName)"
> Search for </el-button
>
<el-button
sizi="mini"
type="warning"
icon="el-icon-refresh-left"
@click="searchName = ''"
> Reset </el-button
>
<el-button
sizi="mini"
@click="handleAdd()"
type="primary"
icon="el-icon-plus"
> newly added </el-button
>
<el-button
@click="getUserList()"
sizi="mini"
icon="el-icon-refresh"
style="float: right"
> Refresh </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=" user name "
prop="username"
align="center"
width="150px"
></el-table-column>
<el-table-column
label=" password "
prop="password"
align="center"
></el-table-column>
<el-table-column label=" operation " align="center">
<template slot-scope="scope">
<el-button size="mini" @click="showEditDialog(scope.row)">
<i class="el-icon-edit" /> edit
</el-button>
<el-button
size="mini"
type="danger"
@click="handleDelete(scope.row)"
>
<i class="el-icon-delete" /> 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: {
// Open the new user window
handleAdd() {
this.dialog = {
show: true,
title: " New users ",
option: "add",
};
this.formData = {
username: "",
password: "",
};
},
// Open the edit user window
showEditDialog(row) {
console.log("row:", row);
this.dialog = {
show: true,
title: " Edit user ",
option: "edit",
};
this.formData = {
id: row.id,
username: row.username,
password: row.password,
};
},
// Get the list of users
async getUserList() {
this.isLoading = true;
let data = await axios.get("http://localhost:3000/users");
this.tableData = data.data.data.users;
this.isLoading = false;
},
// Query according to user name
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;
},
// Delete user
handleDelete(row) {
this.$confirm(" This operation will permanently delete the file , Whether or not to continue ?", " Tips ", {
confirmButtonText: " determine ",
cancelButtonText: " Cancel ",
type: "warning",
})
.then(async () => {
await axios.delete(`http://localhost:3000/users`, {
params: { id: row.id },
});
this.$message({
type: "success",
message: " Delete successful !",
showClose: true,
});
this.getUserList();
})
.catch(() => {
this.$message({
type: "info",
message: " Delete cancelled ",
showClose: true,
});
});
},
// New users
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: " success ",
message: " New user succeeded !",
type: "success",
});
this.getUserList();
},
// Edit user
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: " success ",
message: " Edit user succeeded !",
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=" user name " prop="username">
<el-input
v-model="formData.username"
autocomplete="off"
style="width: 90%"
></el-input>
</el-form-item>
<el-form-item label=" password " 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"> take eliminate </el-button>
<el-button
v-if="dialog.option == 'add'"
@click="addUser('ref_form_userManage')"
type="primary"
> indeed set </el-button
>
<el-button
v-if="dialog.option == 'edit'"
@click="editUser('ref_form_userManage')"
type="primary"
> indeed set </el-button
>
</div>
</el-dialog>
</div>
</template>
<script>
export default {
name: "userManageDialog",
props: ["dialog", "formData"],
data() {
return {
fileList: [],
rules: {
username: [
{ required: true, message: " Please enter the user name ", 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>
Back end :
users.js:
const router = require('koa-router')()
const fs = require("fs")
const uuid = require('uuid');
router.prefix('/users')
// according to username Query the user
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: ' The query fails ' + err })
return console.error(err);
}
resolve({ code: 0, data: JSON.parse(data).users.filter((item) => item.username === username) })
})
})
}
ctx.body = await findJson()
})
// Query all users
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: ' The query fails ' + err })
return console.error(err);
}
resolve({ code: 0, data: JSON.parse(data) })
})
})
}
ctx.body = await findJson()
})
// Delete user
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: ' Delete failed ' + 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: ' Delete failed ' + err })
}
resolve({ code: 0, msg: ' Delete successful ' })
})
})
})
}
ctx.body = await deleteJson()
})
// Add users
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: ' Add failed ' + 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: ' Add failed ' + err })
}
resolve({ code: 0, msg: ' Added successfully ' })
})
})
})
}
// Back to the front end
ctx.body = await writeJson()
})
// Modify the user
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: ' Modification failed ' + 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: ' Modification failed ' + err })
}
resolve({ code: 0, msg: ' Modification successful ' })
})
})
})
}
// Back to the front end
ctx.body = await writeJson()
})
module.exports = router
users.json:
{
"users": [
{
"id": "adfsg",
"username": " Li Si ",
"password": "444asd"
},
{
"id": "d4d2c1df-8c78-4cba-9e42-58c83c26eb5b",
"username": "ag",
"password": "dfg"
},
{
"id": "cadbd3d6-6cab-4f82-ae2d-fe2c0ceae5b7",
"username": "tasdfasd",
"password": "rtasdf"
}
]
}
边栏推荐
- Is "applet container technology" a gimmick or a new outlet?
- COSCon'22 社区召集令来啦!Open the World,邀请所有社区一起拥抱开源,打开新世界~
- 石墨文档:4大对策解决企业文件信息安全问题
- Redis persistence mechanism
- 欧洲生物信息研究所2021亮点报告发布:采用AlphaFold已预测出近1百万个蛋白质
- Pdf batch splitting, merging, bookmark extraction, bookmark writing gadget
- 同一个作业有两个source,同一链接不同数据库账号,为何第二个链接查出来的数据库列表是第一个账号的
- GPT-3当一作自己研究自己,已投稿,在线蹲一个同行评议
- Is the more additives in food, the less safe it is?
- Efficient ETL Testing
猜你喜欢
UE4 blueprint learning chapter (IV) -- process control forloop and whileloop
Pdf batch splitting, merging, bookmark extraction, bookmark writing gadget
Financial professionals must read book series 6: equity investment (based on the outline and framework of the CFA exam)
docker启动mysql及-eMYSQL_ROOT_PASSWORD=my-secret-pw问题解决
企业不想换掉用了十年的老系统
Station B Big utilise mon monde pour faire un réseau neuronal convolutif, Le Cun Forward! Le foie a explosé pendant 6 mois, et un million de fois.
案例推荐丨安擎携手伙伴,保障“智慧法院”更加高效
儿童睡衣(澳大利亚)AS/NZS 1249:2014办理流程
Flutter life cycle
Up to 5million per person per year! Choose people instead of projects, focus on basic scientific research, and scientists dominate the "new cornerstone" funded by Tencent to start the application
随机推荐
DockerMySQL无法被宿主机访问的问题解决
Enterprises do not want to replace the old system that has been used for ten years
华为云GaussDB(for Redis)揭秘第21期:使用高斯Redis实现二级索引
Spark Tuning (II): UDF reduces joins and judgments
Cloud native technology container knowledge points
前置机是什么意思?主要作用是什么?与堡垒机有什么区别?
(1)长安链学习笔记-启动长安链
BasicVSR_ Plusplus master test videos and pictures
同一个作业有两个source,同一链接不同数据库账号,为何第二个链接查出来的数据库列表是第一个账号的
NPM cannot install sharp
(1) Chang'an chain learning notes - start Chang'an chain
浅谈网络安全之文件上传
(shuttle) navigation return interception: willpopscope
Gpt-3 is a peer review online when it has been submitted for its own research
A few suggestions for making rust library more beautiful! Have you learned?
Unified Focal loss: Generalising Dice and cross entropy-based losses to handle class imbalanced medi
Balanced Multimodal Learning via On-the-fly Gradient Modulation(CVPR2022 oral)
docker启动mysql及-eMYSQL_ROOT_PASSWORD=my-secret-pw问题解决
问下各位,有没有flink sql生成作业的文档啊或是案列啊知道flink cli可以建表和指定目
Two week selection of tdengine community issues | phase II