基于Node+axios+mysql+jquery实现前后端分离的增删改查

本文介绍如何使用Node.js和Express框架搭建一个简单的增删改查(CRUD)应用程序,包括连接MySQL数据库、实现HTTP请求处理等关键技术点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录结构
在这里插入图片描述
1、新建文件夹express
2、初始化项目
进入express目录下执行

npm init -y 

3、编写nodeHttp.js文件

const express = require('express');
const db = require("./mysql");
const cors = require("cors")

const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static("./html"));


// 查询
app.get("/allBrand", (req, resp) => {
    const sqlStr = 'select * from brand'
    db.query(sqlStr, (err, results) => {
        // 查询数据失败
        if (err) return console.log(err.message)
        // console.log(results)
        resp.send(results)
    })
})

//插入数据接口
app.post("/addBrand", (req, resp) => {
    // console.log(req.body)
    const sql = 'insert into brand set ?'
    db.query(sql, req.body, (err, res) => {
       if(err)return console.log(err.message);
            resp.send({
                status: 200,
                msg: "修改数据成功"
            })
        
    })
})
//删除接口
app.get("/delete", (req, resp) => {
    let sql = 'delete from brand where id=?'
    db.query(sql, req.query.id, (err, res) => {
        // 注意:执行 delete 语句之后,结果也是一个对象,也会包含 affectedRows 属性
        if (res.affectedRows === 1) {
            resp.send({
                status: 200,
                msg: "修改数据成功"
            })
        }
    })
})
// 根据ID查询
app.get("/selectById", (req, resp) => {
    let sql = 'select * from brand where id=?'
    db.query(sql, req.query.id, (err, results) => {
        // 注意:执行 查询 语句之后,结果也是一个对象,也会包含 RowDataPacket 属性
        if (results.length != 0) {
            // console.log();
            resp.send({
                status: 200,
                msg: "查询成功",
                data: results
            })
        }
    })
})
// //修改数据接口
app.post("/update", (req, resp) => {

    const sql = "update brand set ?  where id=?"
   console.log( req.body);
    db.query(sql, [req.body, req.body.id], (err, res) => {
        // if (err) return console.log(err.message);
        if (res.affectedRows === 1) {
            resp.send({
                status: 200,
                msg: "修改数据成功"
            })
        }
    })
})
// 监听端口
app.listen(80, () => {
    console.log("服务已启动");
})

4、编写mysql.js文件主要用于连接mysql

const mysql = require("mysql");
//如果出现连接不上mysql,请自行百度 (node连接mysql失败)
const db = mysql.createPool({
    host: "localhost",
    user: "root",
    password: "123456",
    database: "gk2022",
    port: '3306'
})

module.exports =db

如果出现连接不上mysql

win+R打开全局控制台,登录mysql数据库
mysql -u root -p123456
修改
 ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';
 刷新
FLUSH PRIVILEGES;

5、编写index.html页面代码(使用了axios和jquery,需要自行下载)

<!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>
    <script src="./axios-0.18.0.js"></script>
    <script src="./jquery.min.js"></script>
    <style>
        #addDiv {
            display: none;
            margin: 0 auto;
            width: 400px;
            height: 400px;
            background: rgb(34, 227, 179);
        }

        .updateDiv {
            display: none;
            margin: 0 auto;
            width: 400px;
            height: 400px;
            background: rgb(34, 227, 179);
        }
    </style>
</head>

<body>
    <input type="button" onclick="switchDiv(1)" value="新增">
    <br>
    <!-- 查询所有 -->
    <table id="brandTable" border="1" cellspacing="0" width="100%"></table>
    <div id="addDiv">
        <h3>添加品牌</h3>
        <form action="" method="post">
            品牌名称:<input id="brandName" name="brandName"><br>
            企业名称:<input id="companyName" name="companyName"><br>
            排序:<input id="ordered" name="ordered"><br>
            描述信息:<textarea rows="5" cols="20" id="description" name="description"></textarea><br>
            状态:
            <input type="radio" name="status" value="0" id="status">禁用
            <input type="radio" name="status" value="1" id="status">启用<br>
            <input type="button" id="addbtn" value="提交">
            <!-- <input type="button" onclick="switchDiv(0)"  value="取消"> -->
        </form>
    </div>
    <div class="updateDiv">
        <h3>修改品牌</h3>
        <form action="" id="updateForm" method="post">
            <input type="hidden" class="id" name="id">
            品牌名称:<input class="brandName" name="brandName"><br>
            企业名称:<input class="companyName" name="companyName"><br>
            排序:<input class="ordered" name="ordered"><br>
            描述信息:<textarea rows="5" cols="20" class="description" name="description"></textarea><br>
            状态:
            <input type="radio" name="status" value="0" class="status">禁用
            <input type="radio" name="status" value="1" class="status">启用<br>
            <input type="button" class="up" onclick="updateBrand()" value="提交">
            <input type="button" class="rem" id="rmupdate" value="取消">

        </form>
    </div>
    <script>
        const userList = () => {
            axios({
                method: "get",
                url: "http://localhost:80/allBrand"
            }).then(function (msg) {
                //获取数据
                let brands = msg.data;
                let tableData = " <tr>\n" +
                    " <th>序号</th>\n" +
                    " <th>品牌名称</th>\n" +
                    " <th>企业名称</th>\n" +
                    " <th>排序</th>\n" +
                    " <th>品牌介绍</th>\n" +
                    " <th>状态</th>\n" +
                    " <th>操作</th>\n" +
                    " </tr>";
                for (let i = 0; i < brands.length; i++) {
                    let brand = brands[i];
                    tableData += "\n" +
                        " <tr align=\"center\">\n" +
                        " <td>" + (i + 1) + "</td>\n" +
                        " <td>" + brand.brandName + "</td>\n" +
                        " <td>" + brand.companyName + "</td>\n" +
                        " <td>" + brand.ordered + "</td>\n" +
                        " <td>" + brand.description + "</td>\n" +
                        " <td>" + brand.status + "</td>\n" +
                        "\n" +
                        " <td><button οnclick=" + 'selectById(' + brand.id + ')' + " >修改</button> <button  οnclick=" + 'deleteBrand(' + brand.id + ')' + ">删除</button></td>\n" +
                        " </tr>";

                }
                // 设置表格数据
                document.getElementById("brandTable").innerHTML = tableData;
            })
        }
        userList()



        // 添加
        $('#addbtn').click(function () {
            // 提交添加表单
            addBrands();
            $("#addDiv").hide();
            $("#btn").show();
            $("table").show();
            // switchDiv(2);
            userList();

        })
        const addBrands = () => {
            var formData = {};
            formData.brandName = $("#brandName").val();
            formData.companyName = $("#companyName").val();
            formData.ordered = $("#ordered").val();
            formData.description = $("#description").val();
            formData.status = $("#status:checked").val();
            axios({
                method: "post",
                url: "http://localhost:80/addBrand",
                data: formData
            }).then(function (resp) {
                console.log(resp)
                if (resp.data.status == 200) {
                    alert(resp.data.msg);
                    userList();
                } else {
                    alert(resp.data.msg);
                }
            })
        }

        // 删除
        const deleteBrand = (id) => {
            axios({
                method: "get",
                url: "http://localhost:80/delete?id=" + id
            }).then(function (resp) {
                console.log(resp);
                if (resp.data.status == 200) {
                    alert(resp.data.msg);
                    // switchDiv(2)
                    userList();
                } else if (res.data.status == 201) {
                    alert(res.data.msg);
                }
            })
        }
        $(".rem").click(function(){
            $(".updateDiv").hide();
                $("table").show();
        })
        // 修改
        const updateBrand = () => {
                $(".updateDiv").hide();
                $("table").show();
            // 获取表单的值
            let updateForm = {};
            updateForm.id = $(".id").val();
            updateForm.brandName = $(".brandName").val();
            updateForm.companyName = $(".companyName").val();
            updateForm.ordered = $(".ordered").val();
            updateForm.description = $(".description").val();
            updateForm.status = $(".status:checked").val();
            axios({
                method: "post",
                url: "http://localhost:80/update",
                data: updateForm
            }).then(function (res) {
                if (res.status == 200) {
                    alert(res.data.msg);
                    userList();
                } else {
                    alert(res.data.msg)
                }
            })
        }

// 根据ID查询
        const selectById = (id) => {
            switchDiv(3)
            axios({
                method: "get",
                url: "http://localhost:80/selectById?id=" + id
            }).then(function (resp) {
                //    表单赋值
                let {data:res} =resp
                let brand = res.data[0];
                console.log(brand);
                // var brand = res.data
                $('#updateForm').find('input[name="id"]').val(brand.id);
                $('#updateForm').find('input[name="brandName"]').val(brand.brandName);
                $('#updateForm').find('input[name="companyName"]').val(brand.companyName);
                $('#updateForm').find('input[name="ordered"]').val(brand.ordered);
                $('#updateForm').find('textarea[name="description"]').val(brand.description);
                $('#updateForm').find('input[name="status"][value="' + brand.status + '"]').attr('checked', 'checked')
            })

        }

        //切换
        function switchDiv(part) {
            //隐藏内容
            $('#addDiv').css("display", "none")
            $('#brandTable').css("display", "none")
            $('#btn').css("display", "none")
            $('.updateDiv').css("display", "none")
            if (1 == part) {//添加页面
                $('#addDiv').css("display", "block")
            } else if (2 == part) {//列表页面
                $('#brandTable').css("display", "block")
            } else if (3 == part) {//编辑页面
                $('.updateDiv').css("display", "block")
            }
        }
    </script>
</body>

</html>

最后执行下面命令安装需要的依赖包

npm i

如果不行,分别执行以下命令

npm i express@4.17.1
cnpm install mysql
cnpm install cors   

结果:
在这里插入图片描述
添加
在这里插入图片描述
修改
在这里插入图片描述
删除
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值