命令行有
npm init -y
node i express
axios.js
// 需要输入的命令行
// 最开始创建文件夹时 npm init -y
// npm i express
// 如果不安装nodemon 梅西修改过后都得重新运行,很麻烦
// 如果之前没有安装 需安装 npm i nodemon -g
// 执行文件 nodemon 文件名
// 或者在package.json增添一下东西
/* "scripts": {
"dev": "nodemon app.js"
}, */
// 执行文件 npm run dev (run可省略)
const fs = require("fs");
const express = require("express");
const app = express();
if (!fs.existsSync("./db")) {
fs.mkdirSync("./db");
}
// 因为前面页面用的是axios,这个让express能够格式化请求体中的json数据
// 否则新增的数据内容无法正常存储,只会存储上id
app.use(express.json());
app.use("/", express.static("./public"));
// ./routes/api/v1/pets.js 这个路径下的文件夹文件都需要自己去创建
// 第一个参数是网址 ,可自己随便命名,但是最好按照api的命名规范,同时要清晰易懂
app.use("/api/v1/pets", require("./routes/api/v1/pets.js"));
// app.use("/api/v1/movies", require("./routes/api/v1/movies.js"));
app.listen(3333, () => {
console.log("服务器运行在3333端口");
}); /* */
pets.js
const router = require('express').Router();
const fs = require('fs');
// /api/v1/pets/--查询所有
router.get('/', (req, res) => {
if (fs.existsSync('./db/pets.json')) {
const pets = JSON.parse(fs.readFileSync('./db/pets.json').toString());
res.json(pets);
} else {
fs.writeFileSync('./db/pets.json', "[]");
res.json([]);
}
});
// /api/v1/pets/:name--根据名字查询信息
router.get('/name', (req, res) => {
// console.log(req.query.name)
console.log(req.query)
const pets = JSON.parse(fs.readFileSync('./db/pets.json').toString());
/* find() 方法返回通过测试( 函数内判断) 的数组的第一个元素的值。
如果没有符合条件的元素返回 undefined
find() 对于空数组, 函数是不会执行的。
find() 并没有改变数组的原始值。 */
const pet = pets.find(item => item.name == req.query.name);
res.json({
code: 1,
info: pet ? pet : {},
});
});
// /api/v1/pets/:id--查询一条信息
router.get('/:id', (req, res) => {
const pets = JSON.parse(fs.readFileSync('./db/pets.json').toString());
const pet = pets.find(item => item.id == req.params.id);
res.json({
code: 1,
info: pet ? pet : {},
});
});
// /api/v1/pets/--存储数据
router.post('/', (req, res) => {
const pets = JSON.parse(fs.readFileSync('./db/pets.json').toString());
pets.push({
id: Date.now(),
...req.body
});
fs.writeFileSync('./db/pets.json', JSON.stringify(pets));
res.json({
code: 1,
msg: '数据存储成功'
});
});
// /api/v1/pets/:id--修改信息
router.put('/:id', (req, res) => {
const pets = JSON.parse(fs.readFileSync('./db/pets.json').toString());
const index = pets.findIndex(item => item.id == req.params.id);
pets[index] = {
id: req.params.id,
...req.body
};
fs.writeFileSync('./db/pets.json', JSON.stringify(pets));
res.json({
code: 1,
msg: '数据修改成功'
});
});
// /api/v1/pets/:id--删除信息
router.delete('/:id', (req, res) => {
const pets = JSON.parse(fs.readFileSync('./db/pets.json').toString());
const index = pets.findIndex(item => item.id == req.params.id);
pets.splice(index, 1);
fs.writeFileSync('./db/pets.json', JSON.stringify(pets));
res.json({
code: 1,
msg: '信息删除成功'
});
});
module.exports = router;
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>信息管理</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- css -->
<style>
#exampleInputAmount {
width: 200px;
}
.form-inline {
margin-bottom: 15px;
}
table tr th {
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<!-- -->
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">列表页</h3>
</div>
<div class="panel-body">
<!-- search---查询 新增 -->
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="searchName" placeholder="请输入姓名">
</div>
<button type="submit" class="btn btn-default btn-primary" id="btnSearch"
onclick="search()">查询</button>
<a href="./add.html" class="btn btn-default btn-danger">新增</a>
</div>
<!-- 列表--查询 -->
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>技能</th>
<th>头像</th>
<th></th>
</tr>
</thead>
<tbody id="list">
<!-- <tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr> -->
</tbody>
</table>
</div>
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>
<script>
// 发起一个get请求,是一个promise对象,成功之后调用then里面的回调函数
// 参数一 表示请求的地址
// axios发送请求的时候content-type默认为application/json,传递的数据是json格式的
// jquery发送请求的时候content-type为url编码的,传递的数据是一个类似于:a=值&b=值2
axios.get('/api/v1/pets')
.then((res) => {
console.log(res);// res.data表示服务器接口输出的内容
let strHtml = '';
res.data.forEach((item, index) => {
strHtml += `
<tr>
<td>${index+1}</td>
<td>${item.name}</td>
<td>${item.age}</td>
<td>${item.edu}</td>
<td><img src="${item.img}"style="width:150px;height:120px;" /></td>
<td>
<button type="submit" class="btn btn-default btn-primary" οnclick="delOne('${item.id}')">删除</button>
<a href="./amend.html?id=${item.id}" class="btn btn-default btn-danger" >修改</a>
</td>
</tr>`;
});
document.getElementById("list").innerHTML = strHtml;
});
// 查询名字
function search() {
var name = document.getElementById('searchName').value;
var str = '';
axios.get('/api/v1/pets/name', {
params: {
name: name
}
})
.then(res => {
console.log(res);
str += `
<tr>
<td>${res.data.info.id}</td>
<td>${res.data.info.name}</td>
<td>${res.data.info.age}</td>
<td>${res.data.info.edu}</td>
<td><img src="${res.data.info.img}" style="width:150px;height:120px;" /></td>
<td>
<button type="submit" class="btn btn-default btn-primary" οnclick="delOne('${res.data.info.id}')">删除</button>
<a href="./amend.html?id=${res.data.info.id}" class="btn btn-default btn-danger" >修改</a>
</td>
</tr>`;
document.getElementById('list').innerHTML = str;
// window.location.reload();
});
}
// 删除
function delOne(id) {
if (confirm('是否删除')) {
axios.delete('/api/v1/pets/' + id)
.then(res => {
window.location.reload();
});
}
}
</script>
</body>
</html>
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>信息录入</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- css -->
<style>
#exampleInputAmount {
width: 200px;
}
.form-inline {
margin-bottom: 15px;
}
table tr th {
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<!-- -->
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">信息录入</h3>
</div>
<div class="panel-body">
<!-- -->
<!-- <form action="" method="POST" role="form"> -->
<legend>信息录入</legend>
<div class="form-group">
<label for="">姓名</label>
<input type="text" class="form-control" placeholder="请输入姓名" id="name">
</div>
<div class="form-group">
<label for="">年龄</label>
<input type="text" class="form-control" placeholder="请输入年龄" id="age">
</div>
<div class="form-group">
<label for="">技能</label>
<textarea type="text" class="form-control" placeholder="请输入技能" id="edu"></textarea>
</div>
<div class="form-group">
<label for="">头像</label>
<input type="text" class="form-control" placeholder="请输入头像地址" id="img">
</div>
<button type="submit" class="btn btn-primary btn-block" onclick="btnSave()">提交</button>
<!-- </form> -->
</div>
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>
<script>
function btnSave() {
var name = document.querySelector('#name').value;
// console.log(imgTxt);
var age = document.querySelector('#age').value;
var edu = document.querySelector('#edu').value;
var img = document.querySelector('#img').value;
if (name && age && edu && img) {
// .post发送post请求
// 参数一 表示地址
// 参数二 表示传递的数据
axios.post('/api/v1/pets', {
name,
age,
edu,
img,
}).then(res => {
console.log(res);
alert('添加成功');
window.location.href = "./index.html";
});
} else {
alert('请填写完整');
}
}
</script>
</body>
</html>
amend.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>信息修改</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- css -->
<style>
#exampleInputAmount {
width: 200px;
}
.form-inline {
margin-bottom: 15px;
}
table tr th {
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<!-- -->
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">信息修改</h3>
</div>
<div class="panel-body">
<!-- -->
<form action="" method="POST" role="form">
<legend>信息修改</legend>
<div class="form-group">
<label for="">姓名</label>
<input type="text" class="form-control" placeholder="请输入姓名" id="name">
</div>
<div class="form-group">
<label for="">年龄</label>
<input type="text" class="form-control" placeholder="请输入年龄" id="age">
</div>
<div class="form-group">
<label for="">技能</label>
<textarea type="text" class="form-control" placeholder="请输入技能" id="edu"></textarea>
</div>
<div class="form-group">
<label for="">头像</label>
<input type="text" class="form-control" placeholder="请输入头像地址" id="img">
</div>
<button type="submit" class="btn btn-primary btn-block" onclick="btnAmend()">提交</button>
</form>
</div>
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>
<script>
// URLSearchParams可以获取当前url中的search值,通过get方法
var params = new URLSearchParams(window.location.search);
var id = params.get('id');
var nameTxt = document.querySelector('#name');
console.log(imgTxt);
var ageTxt = document.querySelector('#age');
var eduTxt = document.querySelector('#edu');
var imgTxt = document.querySelector('#img');
axios.get('/api/v1/pets/' + id)
.then(res => {
nameTxt.value = res.data.info.name;
ageTxt.value = res.data.info.age;
eduTxt.value = res.data.info.edu;
imgTxt.value = res.data.info.img;
});
function btnAmend() {
// if (imgTxt && ageTxt && eduTxt & imgTxt) {
axios.put('/api/v1/pets/' + id, {
name: nameTxt.value,
age: ageTxt.value,
edu: eduTxt.value,
img: imgTxt.value
})
.then(res => {
alert('修改成功');
window.location.href = "./index.html";
});
// }
}
</script>
</body>
</html>