Vue整合Node.js直连Mysql数据库进行CURD操作过程详解

 更新时间:2023年07月18日 10:54:34   作者:豆苗学前端  
这篇文章主要给大家分享Vue整合Node.js,直连Mysql数据库进行CURD操作的详细过程,文中有详细的代码讲解,具有一定的参考价值,需要的朋友可以参考下

1. vue创建项目

vue create xxxx

2. 安装相应的依赖

引入需要的模块(mysql、express、body-parser、cors、vue-resource)

cnpm install mysql --save
cnpm install express --save
cnpm install body-parser --save
cnpm install cors --save
cnpm install vue-resource --save

3.在项目根目录下创建server文件夹:

3.1 在src目录下,main.js中使用vue-resource模块:

// 将vue-resource模块引入进来,否则this.$http将无法使用
import VueResource from 'vue-resource'
Vue.use(VueResource);

3.2 在server目录下,编写database.js:

// 配置数据库相关信息

// 配置数据库相关信息
module.exports = {
  mysql: {
    host: "localhost",
    user: "root",
    password: "root",
    database: "test",
    port: 3306
  }
};

3.3 在server目录下,编写sql.js:

// 编写相关sql语句
let sqlMap = {
  user: {
    // 查询数据
    select: "select * from user where username = ?;",
    // 插入数据
    insert: "insert into user values(?,?);",
    // 修改数据
    update: "update user set password = ? where username = ?;",
    // 删除数据
    delete: "delete from user where username = ? and password = ?;"
  }
};
// 暴露sqlMap
module.exports = sqlMap;

3.4 在server目录下,编写api.js

// 引入database.js文件(配置数据库相关信息)
let models = require('./database');
// 引入sql.js文件(编写相关sql语句)
let $sql = require('./sql');
// 引入mysql和express模块
let mysql = require('mysql');
let express = require('express');
let router = express.Router();
// 开始连接数据库
let conn = mysql.createConnection(models.mysql);
conn.connect();
// 对JSON字符串进行处理
let jsonWrite = function (response, result) {
  if (typeof result === 'undefined') {
    response.json({
      code: '500',
      msg: '操作失败'
    });
  } else {
    response.json(result);
  }
};
// 查询数据('/select')
router.post('/select', (request, response) => {
  // 获取编写相关sql语句
  let sql = $sql.user.select;
  console.log("相关sql语句:", sql);
  // 获取请求参数
  let params = request.body;
  console.log("相关参数", params);
  // [params.username]传参类似mybatis
  conn.query(sql, [params.username], function (error, result) {
    if (error) {
      console.log('网络连接异常:' + error);
    }
    if (result) {
      jsonWrite(response, result);
      for (let i = 0; i < result.length; i++) {
        if (result[i].password == params.password) {
          return response.end();
        } else {
          return response.end();
        }
      }
    }
  })
});
// 插入数据('/insert')
router.post('/insert', (request, response) => {
  // 获取编写相关sql语句
  let sql = $sql.user.insert;
  console.log("相关sql语句:", sql);
  // 获取请求参数
  let params = request.body;
  console.log("相关参数", params);
  // [params.username]传参类似mybatis
  conn.query(sql, [params.username, params.password], function (error, result) {
    if (error) {
      console.log('网络连接异常:' + error);
    }
    if (result) {
      jsonWrite(response, result);
    }
  })
});
// 修改数据('/update')
router.post('/update', (request, response) => {
  // 获取编写相关sql语句
  let sql = $sql.user.update;
  console.log("相关sql语句:", sql);
  // 获取请求参数
  let params = request.body;
  console.log("相关参数", params);
  // [params.username]传参类似mybatis
  conn.query(sql, [params.password, params.username], function (error, result) {
    if (error) {
      console.log('网络连接异常:' + error);
    }
    if (result) {
      jsonWrite(response, result);
    }
  })
});
// 删除数据('/delete')
router.post('/delete', (request, response) => {
  // 获取编写相关sql语句
  let sql = $sql.user.delete;
  console.log("相关sql语句:", sql);
  // 获取请求参数
  let params = request.body;
  console.log("相关参数", params);
  // [params.username]传参类似mybatis
  conn.query(sql, [params.username, params.password], function (error, result) {
    if (error) {
      console.log('网络连接异常:' + error);
    }
    if (result) {
      jsonWrite(response, result);
    }
  })
});
// 暴露router
module.exports = router;

3.5 在serve文件夹下,写入server.js

// 引入api.js
const userApi = require('./api');
// 引入express模块
const express = require('express');
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: false}));
// 访问Node服务端映射地址
app.use('/api', userApi);
// 开始服务器端口
app.listen(8088);
console.log("服务器端口开启成功!");

4. 编写demo2.vue进行交互界面简单编写

// 在路由中引入新demo2.vue页面
import demo2 from "@/components/demo2";
{
   path: '/demo2',
   name: 'demo2',
   component: demo2,
}
<template>
  <div style="margin-left: 100px">
    <h3>数据库增删改查(CURD操作)</h3>
    <label>用户名:<input type="text" v-model="username"/></label><br/><br/>
    <label>密码:<input type="password" v-model="password"/></label><br/><br/>
    <el-button type="primary" @click="selectData">查询</el-button>
    <el-button type="primary" @click="insertData">增加</el-button>
    <el-button type="primary" @click="updateData">修改</el-button>
    <el-button type="primary" @click="deleteData">删除</el-button>
  </div>
</template>
<script>
  export default {
    name: "demo2",
    data() {
      return {
        username: '',
        password: '',
      }
    },
    methods: {
      selectData() {
        // 访问node.js服务端(参数名称:要和api.js中[params.属性名]一致,请求方式也应该保持一致)
        this.$http.post('http://localhost:8088/api/select', {
          username: this.username
        }).then(data => {
          if (data.data[0].username == this.username && data.data[0].password == this.password) {
            this.$message({type: 'success', message: "查询成功"});
          } else {
            this.$message({type: 'warning', message: "查询失败"});
          }
        }).catch(error => {
          this.$message({type: 'error', message: "网络连接异常"});
        });
      },
      insertData() {
        // 访问node.js服务端(参数名称:要和api.js中[params.属性名]一致,请求方式也应该保持一致)
        this.$http.post('http://localhost:8088/api/insert', {
          username: this.username,
          password: this.password
        }).then(data => {
          if (data.data.affectedRows > 0) {
            this.$message({type: 'success', message: "新增成功"});
          } else {
            this.$message({type: 'warning', message: "新增失败"});
          }
        }).catch(error => {
          this.$message({type: 'error', message: "网络连接异常"});
        });
      },
      updateData() {
        // 访问node.js服务端(参数名称:要和api.js中[params.属性名]一致,请求方式也应该保持一致)
        this.$http.post('http://localhost:8088/api/update', {
          username: this.username,
          password: this.password
        }).then(data => {
          if (data.data.affectedRows > 0) {
            this.$message({type: 'success', message: "修改成功"});
          } else {
            this.$message({type: 'warning', message: "修改失败"});
          }
        }).catch(error => {
          this.$message({type: 'error', message: "网络连接异常"});
        });
      },
      deleteData() {
        // 访问node.js服务端(参数名称:要和api.js中[params.属性名]一致,请求方式也应该保持一致)
        this.$http.post('http://localhost:8088/api/delete', {
          username: this.username,
          password: this.password
        }).then(data => {
          if (data.data.affectedRows > 0) {
            this.$message({type: 'success', message: "删除成功"});
          } else {
            this.$message({type: 'warning', message: "删除失败"});
          }
        }).catch(error => {
          this.$message({type: 'error', message: "网络连接异常"});
        });
      }
    }
  }
</script>
<style scoped>
</style>

启动后端

5. 测试:

以上就是Vue整合Node.js直连Mysql数据库进行CURD操作的详细内容,更多关于Vue Node直连Mysql进行CURD操作的资料请关注脚本之家其它相关文章!

相关文章

  • vue3 vscode插件volar配置教程

    vue3 vscode插件volar配置教程

    这篇文章主要介绍了vue3 vscode插件volar配置,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-07-07
  • Vue打包后出现一些map文件的解决方法

    Vue打包后出现一些map文件的解决方法

    本篇文章主要介绍了Vue打包后出现一些map文件的解决方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • vue 封装自定义组件之tabal列表编辑单元格组件实例代码

    vue 封装自定义组件之tabal列表编辑单元格组件实例代码

    这篇文章主要介绍了vue 封装自定义组件tabal列表编辑单元格组件实例代码,需要的朋友可以参考下
    2017-09-09
  • vue 动态样式绑定 class/style的写法小结

    vue 动态样式绑定 class/style的写法小结

    这篇文章主要介绍了vue 动态样式绑定 class/style的写法小结,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-03-03
  • 浅谈VUE中演示v-for为什么要加key

    浅谈VUE中演示v-for为什么要加key

    这篇文章主要介绍了浅谈VUE中演示v-for为什么要加key,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-01-01
  • SpringBoot+Vue 前后端合并部署的配置方法

    SpringBoot+Vue 前后端合并部署的配置方法

    这篇文章主要介绍了SpringBoot+Vue 前后端合并部署的配置方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • 详解vue-cli4 配置不同开发环境打包命令

    详解vue-cli4 配置不同开发环境打包命令

    这篇文章主要介绍了vue-cli4 配置不同开发环境打包命令,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-07-07
  • VUE页面中加载外部HTML的示例代码

    VUE页面中加载外部HTML的示例代码

    本篇文章主要介绍了VUE页面中加载外部HTML的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • 基于Vue.js实现tab滑块效果

    基于Vue.js实现tab滑块效果

    这篇文章主要为大家详细介绍了基于Vue.js实现tab滑块效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-07-07
  • vue关于点击详情页面keep-alive的缓存问题

    vue关于点击详情页面keep-alive的缓存问题

    这篇文章主要介绍了vue关于点击详情页面keep-alive的缓存问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06

最新评论