2023-08-09静态html+node+mysql+navi

2023-08-08  本文已影响0人  swp小小喀嚓鱼

前端 xx.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">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcss.com/qs/6.7.0/qs.min.js"></script>
    <title>Document</title>
</head>

<body>
    <button class="btn1">获取数据</button>
    <button class="btn2">新增数据</button>
    <button class="btn3">修改数据</button>
    <button class="btn4">删除数据</button>
    <script>
        var qs = Qs
        let btn1 = document.getElementsByClassName('btn1')[0]
        let btn2 = document.getElementsByClassName('btn2')[0]
        let btn3 = document.getElementsByClassName('btn3')[0]
        let btn4 = document.getElementsByClassName('btn4')[0]


       
        function getxx(method, path, redata = {}) {
            return new Promise((resolve, reject) => {
                axios({
                    url: `http://localhost:8111/${path}`,
                    method,
                    [method.toLowerCase() === 'get' ? 'params' : 'data']: redata
                    // params: {},
                    // data:{},
                }).then((res) => {
                    resolve(res)
                })
            })
        }

        btn1.addEventListener('click', async () => {
            let resutl = await getxx('get', 'getPeople')
            console.log(resutl)
        })

        btn2.addEventListener('click', async () => {
            let resut2 = await getxx('post', 'submitPeople', qs.stringify({ pwd: 123456, name: 'duobear1' }))
            // let resut2 = await getxx('post', 'submitPeople', JSON.stringify({ firstName: 'Fred', lastName: 'duoe' })) //效果不好
            // let resut2 = await getxx('post', 'submitPeople', { firstName: 'Fred', lastName: 'duoe' }) //不行
            console.log(resut2)
        })


        btn3.addEventListener('click', async () => {
            let resut3 = await getxx('post', 'updatePeople', qs.stringify({ id: 5, name: 'duobear888' }))
            console.log(resut3)
        })

        btn4.addEventListener('click', async () => {
            let resut4 = await getxx('post', 'delPeople', qs.stringify({ id: 5 }))
            console.log(resut4)
        })
    </script>

</body>

</html>

后端 xx.js文件

const express = require('express');
const mysql = require('mysql');
// const bodyParser = require("body-parser");
const cors = require('cors');


const app = express()
app.use(cors())
// app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.urlencoded({ extended: false }))



// 创建连接对象 createPool
// createConnection  connection
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    port: 3307,
    database: 'demo1'

})

// 查询数据
app.get('/getPeople', (req, res) => {
    connection.query('select * from users', (err, results, fields) => {
        if (err) {
            result = { warn: 'err', message: '获取数据库时发生搓搓' }
            res.send(JSON.stringify(result))
        } else {
            res.send(JSON.stringify(results))
        }

    })
})

// 插入数据
app.post('/submitPeople', (req, res) => {
    const sql = 'insert into users set ?';
    connection.query(sql, req.body, function (error, results) {
        if (error) {
            result = { warn: 'err', message: '插入数据库时发生搓搓' }
            res.send(JSON.stringify(result))
        } else {
            res.send(JSON.stringify({ msg: 'ok', results: results.insertId }))
        }

    });



})


// 更新数据
app.post('/updatePeople', (req, res) => {
    const updatesql = 'update users set name = ? where id= ?';
    const { id, name } = req.body
    const arrdata = [name, id]
    // const arrdata = ['duobear999', 5]
    connection.query(updatesql, arrdata, function (error, results) {
        if (error) {
            result = { warn: 'err', message: '更新 数据库时发生搓搓' }
            res.send(JSON.stringify(result))
        } else {
            res.send(JSON.stringify({ msg: 'ok', results: results.affectedRows }))
        }
    });

})

// 删除数据
app.post('/delPeople', (req, res) => {
    const delsql = 'delete from users  where id= ?';
    const { id } = req.body
    connection.query(delsql, id, function (error, results) {
        if (error) {
            result = { warn: 'err', message: '删除 数据库时发生搓搓' }
            res.send(JSON.stringify(result))
        } else {
            res.send(JSON.stringify({ msg: 'ok', results: results.affectedRows }))
        }

    });

})


app.listen(8111, () => {
    console.log('服务器已经启动')
})



package.json

{
  "dependencies": {
    "body-parser": "^1.20.2",
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "mysql": "^2.18.1"
  }
}

navicat
[图片上传失败...(image-daa23-1691562070689)]

后端启动服务
1,需要提前下载好依赖
2:node xx.js 启动后端服务

前端启动服务
主要借助vscode中的插件live server,运行静态文件xx.html

上一篇下一篇

猜你喜欢

热点阅读