Node.js

实现简单前后端完全分离增删改查:node.js+mysql+vue

Nick · 2月13日 · 2020年 · 本文9049字 · 阅读23分钟1,248

1. node.js+mysql实现后台接口

配置环境

  • 选择一个空文件夹初始化项目,命令框中输入
    npm init
  • 安装要用到几个模块
    npm install express body-parser mysql cors --save
  • 建立数据库表

在根目录创建一个 index.js 文件

后端代码如下

/* 引入express框架 */
const express = require('express');
var router = express.Router();
const app = express();
/* 引入cors */
const cors = require('cors');
app.use(cors());
/* 引入body-parser */
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
/* 引入mysql */
const mysql = require('mysql');
const conn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'test',
    multipleStatements: true
})
conn.connect();
/* 监听端口 */
app.listen(3000, () => {
    console.log('——————————服务已启动——————————');
})
app.get('/', (req, res) => {
    res.send('<p style="color:red">服务已启动</p>');
})
//查
app.get('/api/getUserList', (req, res) => {
    const sqlStr = 'SELECT * FROM users'
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({
            code: 404,
            message: error
        })
        res.json({
            code: 200,
            message: results,
            affextedRows: results.affextedRows
        })
    })
})
//条件查找
app.get('/api/getUserListById/:id', (req, res) => {
    const id = req.params.id;
    const sqlStr = 'select * from users where id=?';
    conn.query(sqlStr, id, (err, results) => {
        if (err) return res.json({
            code: 404,
            message: '数据不存在',
            affextedRows: 0
        });
        res.json({
            code: 200,
            message: results,
            affextedRows: results.affextedRows
        });
    })
});
//添加
app.post('/api/addUser', (req, res) => {
    console.log(req.body);
    const username = req.body.username;
    const sex = req.body.sex;
    const address = req.body.address;
    console.log("username:" + username);
    // const sqlStr = "insert into users(username,sex,address) values('" + username + "','" + sex + "','" + address + "')";
    const sqlStr = "insert into users set ?";
    console.log(sqlStr);
    conn.query(sqlStr, req.body, (err, results) => {
        if (err) return res.json({
            code: 404,
            message: err,
            affectedRows: 0
        });
        res.json({
            code: 200,
            message: '添加成功',
            affectedRows: results.affectedRows
        });
    })
});
//修改
app.post('/api/updateUser', function (req, res) {
    console.log(req.body);
    const id = req.body.id;
    const username = req.body.username;
    const sex = req.body.sex;
    const address = req.body.address;
    const sqlStr = "update users set username='" + username + "',sex='" + sex + "',address='" + address + "'where id=" + id;
    console.log(sqlStr);
    conn.query(sqlStr, (err, results) => {
        if (err) return res.json({
            code: 404,
            message: err,
            affectedRows: 0
        });
        res.json({
            code: 200,
            message: '修改成功',
            affectedRows: results.affectedRows
        });
    })
});
//删除
app.delete('/api/deleteUser/:id', function (req, res) {
    console.log('params:' + req.params);
    let id = req.params.id;
    let sql = 'delete from users where id=' + id;
    conn.query(sql, id, (err, results) => {
        if (err) return res.json({
            code: 404,
            message: err,
            affectedRows: 0
        });
        res.json({
            code: 200,
            message: '删除成功',
            affectedRows: results.affectedRows
        })
    })
});

在vscode中启动该服务器(运行index.js文件)
实现简单前后端完全分离增删改查:node.js+mysql+vue-左眼会陪右眼哭の博客
服务器启动后,就可以通过用链接的方式生成接口,访问到数据库里面的数据

返回的是json数据

然后我们可以写一个前端项目来调用这个后台的api接口

2. vue+element ui+axios实现前端渲染

(由于不是大项目,全部使用CDN链接资源)
在根目录新建一个文件 index.html
代码如下

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

<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">
    <title>node.js编写接口</title>
    <!-- element-ui 的样式表文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/element-ui/2.12.0/theme-chalk/index.css" rel="nofollow noopener"  />
    <script src="https://cdn.staticfile.org/vue/2.5.22/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/vue-router/3.0.1/vue-router.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <!-- element-ui 的 js 文件 -->
    <script src="https://cdn.staticfile.org/element-ui/2.12.0/index.js"></script>
    <style>
        .el-header {
            background-color: #283a50;
            display: flex;
            justify-content: space-between;
            padding-left: 0;
            align-items: center;
            color: #fff;
            font-size: 20px;
        }

        .el-header div {
            display: flex;
            align-items: center;
        }

        .el-header span {
            margin-left: 15px;
        }

        .el-main {
            background-color: #eaedfa;
            min-height: 650px;
        }

        .add {
            display: block;
            width: 200px;
            margin: 20px auto;
        }
    </style>
</head>

<body>
    <div id="app">
        <el-header>
            <div>
                <img src="http://qiniu.qkongtao.cn/2020/02/logo1.fa9c5aaa.png" width="60px"
                    height="60px" />
                <span>简单的增删改查</span>
            </div>
        </el-header>
        <!-- 页面主题区域 -->
        <el-container>
            <!-- 内容主体 -->
            <el-main>
                <el-button type="primary" @click="showAddDialog" class="add">添加用户</el-button>
                <el-table :data="userList" border stripe>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="姓名" prop="username"></el-table-column>
                    <el-table-column label="性别" prop="sex"></el-table-column>
                    <el-table-column label="地址" prop="address"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <!-- 修改按钮 -->
                            <el-tooltip class="item" effect="dark" content="修改用户" placement="top" :enterable="false">
                                <el-button type="primary" icon="el-icon-edit" size="mini"
                                    @click="showEditDialog(scope.row.id)"></el-button>
                            </el-tooltip>
                            <!-- 删除按钮 -->
                            <el-tooltip class="item" effect="dark" content="删除用户" placement="top" :enterable="false">
                                <el-button type="danger" icon="el-icon-delete" size="mini"
                                    @click="removeUserById(scope.row.id)"></el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </el-main>
        </el-container>
        <!-- 添加用户的对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <!-- 内容主题区域 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-input v-model="addForm.sex"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="addForm.address"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="adduser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户对话框 -->
        <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <!-- 内容主题区域 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-input v-model="editForm.sex"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="editForm.address"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</body>
<script>
    axios.defaults.baseURL = 'http://localhost:3000/api/'
    Vue.prototype.$http = axios

    var vm = new Vue({
        el: '#app',
        data: {
            //全部数据列表
            userList: [],
            addDialogVisible: false,
            addForm: {
                username: '',
                sex: '',
                address: ''
            },
            addFormRules: {
                username: [{
                    required: true,
                    message: '请输入姓名',
                    tirgger: 'blur'
                }],
                sex: [{
                    required: true,
                    message: '请输入性别',
                    tirgger: 'blur'
                }],
                address: [{
                    required: true,
                    message: '请输入地址',
                    tirgger: 'blur'
                }],
            },
            editDialogVisible: false,
            editForm: {
                username: '',
                sex: '',
                address: ''
            },
            editFormRules: {
                username: [{
                    required: true,
                    message: '请输入姓名',
                    tirgger: 'blur'
                }],
                sex: [{
                    required: true,
                    message: '请输入性别',
                    tirgger: 'blur'
                }],
                address: [{
                    required: true,
                    message: '请输入地址',
                    tirgger: 'blur'
                }],
            },



        },
        created() {
            this.getUserList()
        },
        methods: {
            async getUserList() {
                const {
                    data: res
                } = await this.$http.get('getUserList')
                console.log(res);
                this.userList = res.message
            },
            showAddDialog() {
                this.addDialogVisible = true
            },
            async showEditDialog(id) {
                const {
                    data: res
                } = await this.$http.get('getUserListById/' + id)
                if (res.code != 200) {
                    return this.$message.error('查询用户信息失败!')
                }
                this.editForm = res.message[0]
                this.editDialogVisible = true
            },
            adduser() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) return
                    //可以发起添加用户的网络请求
                    const {
                        data: res
                    } = await this.$http.post('addUser', this.addForm)
                    console.log('res :', res);
                    if (res.code != 200) {
                        return this.$message.error('添加用户失败!')
                    }
                    this.$message.success('添加用户成功!')
                    // 隐藏添加用户的对话框
                    this.addDialogVisible = false
                    //重新获取用户列表数据
                    this.getUserList()
                })
            },
            editUser() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) return
                    //可以发起添加用户的网络请求
                    const {
                        data: res
                    } = await this.$http.post('updateUser', this.editForm)
                    console.log('res :', res);
                    if (res.code != 200) {
                        return this.$message.error('修改用户失败!')
                    }
                    this.$message.success('修改用户成功!')
                    // 隐藏添加用户的对话框
                    this.editDialogVisible = false
                    //重新获取用户列表数据
                    this.getUserList()
                })
            },
            addDialogClosed() {
                //对话框关闭后自动重置
                this.$refs.addFormRef.resetFields()
            },
            editDialogClosed() {
                //对话框关闭后自动重置
                this.$refs.editFormRef.resetFields()
            },
            async removeUserById(id) {
                //弹框询问是否删除
                const confirmResult = await this.$confirm(
                    '此操作将永久删除该用户, 是否继续?',
                    '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).catch(err => {
                    return err
                })
                //如果用户确认删除,则返回值为字符串confirm
                //如果用户取消了删除,则返回值为字符串cancel
                // console.log(confirmResult);
                if (confirmResult === 'cancel') {
                    return this.$message.info('已经取消了删除')
                }
                const {
                    data: res
                } = await this.$http.delete('deleteUser/' + id)
                if (res.code != 200) {
                    return this.$message.error('删除用户失败!')
                }
                this.$message.success('删除用户成功!')
                this.getUserList()
            },
        },
    })
</script>

</html>

然后直接运行index.html文件

实现效果如下

  • 添加用户
  • 修改用户
  • 删除用户

界面效果都是用 element ui 做的,效果还可以

3. 总结

    由于这段时间都在学vue + element ui 的电商后台项目,但是全端渲染中都是用的别人写好的api接口文档,然后自己也想学着写后台api接口,之前学过node.js,但是也只会基础,然后就学着用node.js学着做简单的接口文档,今天就搞了一下简单的增删改查。现在接触到的前后端有两种形式,一种是ssm框架,在jsp上用session等会话机制来实现数据渲染,一种是node.js,Node.js分为两种模式,一种为后台渲染,一种前端渲染,后端渲染使用的是模板引擎,如ejs,swig模板文件,但是这都是后端渲染,弱化了前端;后来学了vue,接触到了Vue中各种强大的东西,如双向绑定机制,路由,axios,vuex,各种等。然后真正的体验到了前后端的完全分离模式,是前端的工程项目。
    我觉得写api接口文档挺有意思的,因为如果把写好的接口用pm2部署到服务器上,那有接口文档的人都可以远程使用接口数据,爬虫得出来的数据大概就是这个意思吧!

0 条回应
在线人数:1人 来访统计
说谎
林宥嘉
隐藏