nodejs+mysql实现增删改查

首先来看一下nodejs里面的配置

1.首先是里面所有需要下载的依赖包,包括express框架,bodyParser解析中间件,mysql数据库的依赖,包括设置跨域。

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');
//这里配置连接池以链接数据库
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    // port: '3306',
    database: 'nodemysql',
    useConnectionPooling: true
})


connection.connect(function () {
    console.log('连接成功')

});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}))
//设置跨域访问
app.all('*', function (req, res, next) {
    //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header('Access-Control-Allow-Headers', 'Content-type');
    //跨域允许的请求方式
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,PATCH");
    //可选,用来指定本次预检请求的有效期,单位为秒。在此期间,不用发出另一条预检请求。
    res.header('Access-Control-Max-Age', 1728000);//预请求缓存20天
    next();
});

2.接下来就是增删改查了,里面涉及到一些简单的sql语句

//  查询
app.get('/getdata', (req, res) => {
//查询名为posts的表
    let sql = 'select * from posts';
    connection.query(sql, (err, results) => {
        if (err) return res.json({
            code: 100,
            data: '没有内容'
        });
        res.json({
            code: 200,
            data: results
        });

    })
    // connection.end()
});

//插入数据
app.post('/insertdata', (req, res) => {
    let params = [req.body.name, req.body.age, req.body.school, req.body.discribe] //  传来的参数
    let addsql = `insert into posts(name,age,school,discribe) value (?,?,?,?)` //  插入语句,?代表插入的值,要插入到posts表内容
    let test = new Promise((resolve, reject) => {
        connection.query(addsql, params, (err, result) => {
            err ? reject(`插入失败`) : resolve(result)
        })
    })
    test.then(result => {
        connection.query('select last_insert_id()', (err, results) => {
            //  last_insert_id是获取表中最后一条数据
            res.json({
                code: 200,
                data: {
                    // id: results[0]['last_insert_id()'],
                    name: req.body.name,
                    age: parseInt(req.body.age),
                    school: req.body.name,
                    discribe: req.body.discribe
                }
            });
        })
    }).catch(err => {
        res.json({
            code: 100,
            data: `插入数据有误`
        })
    })
});

//  编辑
app.post('/updatedata', (req, res) => {
    let [params, addsql] = [
        [req.body.name, req.body.age, req.body.school, req.body.discribe],
        `update posts set name = ? , age = ? , school = ? , discribe = ? where id = ${req.body.id}`
    ]
    let selectSql = `select id,name,age,school,discribe from posts where id=${req.body.id}`
    let update = new Promise((resolve, reject) => {
        connection.query(addsql, params, (err, result) => {
            err ? reject(`插入失败`) : resolve(result)
        })
    })
    update.then(result => {
        connection.query(selectSql, req.body.id, (err, results) => {
            if (err) {
                return res.json({
                    code: 200,
                    data: []
                });
            } else {
                res.json({
                    code: 200,
                    data: results
                });
            }
        })
    }).catch(err => {
        res.json({
            code: 100,
            data: '编辑失败'
        });
    })
})

//  删除
app.post('/deletedata', (req, res) => {
    let [params, addsql] = [
        [req.body.id],
        'delete posts from posts where id = ? '
    ]
    let test = new Promise((resolve, reject) => {
        connection.query(addsql, params, function (err, result) {
            err ? reject(`删除失败`) : resolve(result)
        })
    })
    test.then(result => {
        res.json({
            code: 200,
            data: `删除成功`
        })
    }).catch(err => {
        res.json({
            code: 100,
            data: '删除失败'
        })
    })
});

3.配置服务器端口,虽然写在最下面,但这是第一步噢,不然在网页里面是访问不了的。

//配置服务端口 
var server = app.listen(3000, function () {
    const hostname = 'localhost';
    const port = 3000;
    console.log(`Server running at http://${hostname}:${port}/`);
})

html页面的代码,用elementui搭建的简单页面,里面无非就是拿我们配置好的接口调取数据渲染。

image.png
<!DOCTYPE html>
<html lang="en">

<head>

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
        <!-- 引入样式 -->
        <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
        <!-- 引入组件库 -->
        <script src="https://unpkg.com/element-ui/lib/index.js"></script>
        <title>Document</title>
    </head>

    <style>
        body {
            background-color: #f7f7f7;
            margin: 0;
        }

        #app {
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 1px 4px #e7e7e7, 0 5px 40px #e9e9e9 inset;
        }
    </style>

<body>
    <div id="app">
        <template>
            <el-button type="primary" @click="add" style="margin-bottom:20px;" size="medium">
                添加数据
            </el-button>
            <el-table :data="tableData" style="width: 100%">
                <el-table-column prop="name" label="名字" width="180">
                </el-table-column>
                <el-table-column prop="age" label="年龄" width="180">
                </el-table-column>
                <el-table-column prop="school" label="学校" width="180">
                </el-table-column>
                <el-table-column prop="discribe" label="介绍">
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button @click="handleEdit(scope.row)" size="small">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-dialog title="填写信息" :visible.sync="dialogFormVisible" :before-close="cancel">
                <el-form :model="form">
                    <el-form-item label="名字" label-width="200">
                        <el-input v-model="form.name" placeholder="请输入名字"></el-input>
                    </el-form-item>
                    <el-form-item label="年龄" label-width="200">
                        <el-input v-model="form.age" placeholder="请输入年龄" type="number" min="0"></el-input>
                    </el-form-item>
                    <el-form-item label="学校" label-width="200">
                        <el-input v-model="form.school" placeholder="请输入学校"></el-input>
                    </el-form-item>
                    <el-form-item label="介绍" label-width="200">
                        <el-input v-model="form.discribe" placeholder="请输入介绍"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancel">取 消</el-button>
                    <el-button type="primary" @click="submit">确 定</el-button>
                </div>
            </el-dialog>
        </template>
    </div>

    <script>
        new Vue({
            el: '#app',
            data: {
                tableData: [],
                dialogFormVisible: false,
                form: {
                    name: '',
                    age: '',
                    school: '',
                    discribe: ''
                },
                submitState: 0,
            },
            mounted() {
                this.getData()
            },
            methods: {
                //  简单封装g请求 url:请求地址  params:参数   showNotify:是否显示错误弹出框 默认显示
                getAxios(url, params, showNotify) {
                    return new Promise((resolve, reject) => {
                        axios({
                            method: params ? 'post' : 'get',
                            url: url,
                            data: params
                        }).then(res => {
                            if (res.data.code == 200) {
                                resolve(res)
                            } else {
                                reject(`${res.data.data}`)
                                this.$notify({
                                    title: '警告',
                                    message: res.data.data,
                                    type: 'warning'
                                })
                            }
                        }).catch(err => {
                            reject(err)
                            showNotify ? '' : this.$notify({
                                title: '警告',
                                message: err,
                                type: 'warning'
                            })
                        })
                    })
                },
                //  获取数据
                getData() {
                    this.getAxios(`http://localhost:3000/getdata`).then(res => {
                        this.tableData = res.data.data
                    })
                },
                //  编辑
                handleEdit(i) {
                    this.submitState = 1
                    this.form = i
                    this.dialogFormVisible = true
                },
                //  删除
                handleDelete(i) {
                    this.$confirm('确认要删除么', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        this.getAxios(`http://localhost:3000/deletedata`, {
                            id: i.id
                        }).then(res => {
                            this.tableData.splice(this.tableData.findIndex(e => e.id == i.id), 1)
                        })
                    })
                },
                //  提交编辑
                submit() {
                    if (this.submitState == 0) {
                        this.getAxios(`http://localhost:3000/insertdata`, this.form).then(res => {
                            this.tableData.push(res.data.data)
                            this.dialogFormVisible = false
                            this.form = {}
                        })
                    } else {
                        this.getAxios(`http://localhost:3000/updatedata`, this.form).then(res => {
                            // this.tableData[this.tableData.findIndex(e => e.id == this.form.id)] = res.data.data[0]
                            this.getData()
                            this.dialogFormVisible = false
                        })
                    }

                },
                //  添加
                add() {
                    this.submitState = 0
                    this.dialogFormVisible = true
                },
                cancel() {
                    this.form = {
                        name: '',
                        age: '',
                        school: ''
                    }
                    this.dialogFormVisible = false
                },
            }
        })
    </script>
</body>
</html>
到这里就结束了,小伙伴们可以试试噢。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。