node.js项目

140 阅读2分钟

后台


import express from "express"
import fs from "fs-then"
import cors from "cors"
import bodyParser from "body-parser"
const app = express()
// 解决跨域
app.use(cors())
app.use(bodyParser.json())
// 获取
// 定义接口
// - 接口名称:/api/getbooks  
// - 请求方式:GET
// - 请求参数:无
// - 响应数据:`{ status: 0, message: '获取图书成功', data: [ { 一本书 }, { 一本书 } ] }`
app.get("/api/getbooks", async (req, res) => {
    // 读取本地文件
    const data = await fs.readFile("./data/01.json", "utf-8")
    // 响应回前端
    res.send({ status: 0, message: '获取图书成功', data: JSON.parse(data) })
})
//获取编辑接口
app.get("/api/getid", async (req, res) => {
    // 读取本地文件
    const data = JSON.parse(await fs.readFile("./data/01.json", "utf-8"))
    const index = data.find(item => item.id == req.query.id)
    if (index) {
        res.send({ status: 0, message: '获取图书成功', data: index })

    } else {
        res.send({ status: 1, message: 'ID不存在', data: index })
    }
})

// 新增
// - 接口名称:/api/addbook 
// - 请求方式:POST
// - 请求体:bookname (书名)、author(作者)、publisher(出版社)
// - Content-Type: application/x-www-form-urlencoded
// - 响应数据:`{ status: 0, message: '添加图书成功' }`
// 设置express支持post请求
app.use(express.urlencoded());
app.post("/api/addbook", async (req, res) => {
    let data = await fs.readFile("./data/01.json", "utf-8")
    data = JSON.parse(data)
    data.push({ ...req.body, id: Date.now() })
    await fs.writeFile("./data/01.json", JSON.stringify(data))
    res.send({ status: 0, message: '添加图书成功' })
})

// 修改
// - 接口名称:/api/updatebook
// - 请求方式:PUT
// - 请求体:id(ID)、bookname (书名)、author(作者)、publisher(出版社)
// - Content-Type: application/x-www-form-urlencoded  
// - 响应数据:`{ status: 0, message: '修改图书成功' }`
app.put("/api/updatebook", async (req, res) => {
    let data = await fs.readFile("./data/01.json", "utf-8")
    data = JSON.parse(data)
    console.log(req.body);
    const index = data.findIndex(item => item.id == req.body.id)
    if (index === -1) {
        res.send({ status: 1, message: '不存在id' })
    } else {
        data[index] = req.body
        await fs.writeFile("./data/01.json", JSON.stringify(data))
        res.send({ status: 0, message: '修改图书成功', data })
    }
})

// 删除
// - 接口名称:/api/delbook
// - 请求方式:DELETE
// - 请求参数:id(ID)  放在 url上!! 
// - 响应数据:`{ status: 0, message: '删除图书成功' }`
app.delete("/api/delbook", async (req, res) => {
    let data = await fs.readFile('./data/01.json', "utf-8")
    data = JSON.parse(data)
    const id = req.query.id
    const index = data.findIndex(item => {
        console.log(item.id);
        console.log(id);
        return item.id == id
    })
    console.log(index);
    if (index === -1) {
        res.send({ status: 0, message: '删除图书失败' })
    } else {
        data.splice(index, 1)
        await fs.writeFile("./data/01.json", JSON.stringify(data))
        res.send({ status: 0, message: '删除图书成功' })
    }

})


// 开启端口
app.listen(8080, () => {
    console.log("开启成功");
}) 

渲染、删除界面

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
    <div class="main">
        <table>
            <thead>
                <th>ID</th>
                <th>书名</th>
                <th>作者</th>
                <th>出版社</th>
                <th>操作</th>

            </thead>
            <tbody>

            </tbody>
        </table>
        <!-- 引入axios -->
    </div>
    <script src="../js/axios.js"></script>
    <script>
        window.onload = function () {
            let tbody = document.querySelector(".main table tbody")
            // 获取书籍数据
            async function getbooks() {
                const res = await axios.get("http://127.0.0.1:3000/api/getbooks")
                // console.log(res);
                const list = res.data.data
                console.log(list);
                let html = ``
                list.forEach(item => {
                    html += `
           <tr>
             <td>${item.id}</td>	                  
             <td>${item.bookname}</td>      
             <td>${item.author}</td>
             <td>${item.publisher}</td>
             <td><button class="btnDel" data-id="${item.id}">删除</button><button class="btnEdi" data-id="${item.id}"> <a href="./editbook.html?id=${item.id}" target="_blank">编辑</a></button></td>
         
           </tr>
           `
                });
                tbody.innerHTML = html
            }
            getbooks()


            // 删除

            tbody.addEventListener("click", async function (e) {
                if (e.target.className == "btnDel") {
                    let id = e.target.dataset.id
                    console.log(id);
                    let res = await axios.delete('http://127.0.0.1:8080/api/delbook',
                        { params: { id } })
                    console.log(res);
                    getbooks()
                }
            })

        }
    </script>
</body>

</html>

新增界面


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .main {
            width: 600px;
            margin: 50px auto;
            border: 1px solid #ccc;
        }
    </style>
</head>

<body>
    <div class="main">
        <div>
            <label for="">书名</label> <input class="bookname" type="text" />
        </div>
        <div><label for="">作者</label> <input class="author" type="text" /></div>
        <div>
            <label for="">出版社</label> <input class="publisher" type="text" />
        </div>
        <div>
            <button>新增</button>
        </div>
    </div>
</body>
<script src="../js/axios.js"></script>
<script>

    let add = document.querySelector("button")

    add.addEventListener("click", async function (e) {
        let bookname = document.querySelector(".bookname").value
        let author = document.querySelector(".author").value
        let publisher = document.querySelector(".publisher").value
        console.log(bookname, author, publisher);
        // 绑定新增接口
        let res = await axios.post('http://127.0.0.1:8080/api/addbook', {
            bookname,
            author,
            publisher
        })
        console.log(res);
    })
</script>

</html>

编辑界面

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .main {
            width: 600px;
            margin: 50px auto;
            border: 1px solid #ccc;
        }
    </style>
</head>

<body>
    <h1>编辑页面</h1>
    <div class="main">
        <div>
            <label for="">书名</label> <input class="bookname" type="text" />
        </div>
        <div><label for="">作者</label> <input class="author" type="text" /></div>
        <div>
            <label for="">出版社</label> <input class="publisher" type="text" />
        </div>
        <div>
            <button class="btnEdi">编辑</button>
        </div>
    </div>
    <script src="../js/axios.js"></script>
    <script>
        const arr = location.search.split('=')
        const id = arr[arr.length - 1]
        let btnEdi = document.querySelector(".btnEdi")
        axios.get('http://127.0.0.1:8080/api/getid', {
            params: { id }
        }).then(res => {
            // console.log(res);
            let data = res.data.data
            console.log(data);
            document.querySelector('.bookname').value = data.bookname
            document.querySelector('.author').value = data.author
            document.querySelector('.publisher').value = data.publisher
        })
        btnEdi.addEventListener('click', async function () {
            let bookname = document.querySelector(".bookname").value
            let author = document.querySelector(".author").value
            let publisher = document.querySelector(".publisher").value
            console.log(bookname, author, publisher);
            // 绑定编辑接口
            let res = await axios.put('http://127.0.0.1:8080/api/updatebook', {
                id,
                bookname,
                author,
                publisher
            })
            console.log(res);
        })
    </script>
</body>

</html>