在 vue 中通过 express 连接数据库

需要 vue cli3+,node,express 4.17.1+, MySQL

小白一个,写毕业设计遇到的问题,在这里记录一下

在网上找到的,然后自己写了一遍这里记录一下
原链接

大佬有什么好的建议尽情来说

一、首先创建一个数据库

 # 创建数据库
 CREATE DATABASE my\_db\_01

 # 使用这个数据库
 USE my\_db\_01

 # 创建测试表
 CREATE TABLE test(
  id INT AUTO\_INCREMENT PRIMARY KEY, # 该字段为主键且自增
  user\_name VARCHAR(20), # 用户名
  age TINYINT # 年龄
 )

 # 测试插入成功
 INSERT INTO test(user\_name, age) VALUES('zs', '18')

 # 查看表所有数据
 SELECT \* FROM test

在 vue 中通过 express 连接数据库_第1张图片

二、初始化 vue 项目

vue create test

下载 express 模块(搭建一个简单服务器)

npm i express

下载 MySQL 模块

npm i mysql

下载 axios 模块

npm i --save axios

执行 npm run serve ,能否正常启动

在 vue 中通过 express 连接数据库_第2张图片

三、创建一个简单服务器并写入 sql 语句

  1. 在项目根目录创建 server 文件夹然后里面创建三个 .js 文件和一个 api 文件夹

在 vue 中通过 express 连接数据库_第3张图片

  1. db.js 中配置MySQL
// 连接数据库配置
 module.exports = {
  mysql: {
  host: 'localhost', // 域名,这是本机域名
  user: 'root', // MySQL 登录用户名
  password: 'hongyun0808', // MySQL 登录密码 一般都是 root
  database: 'my\_db\_01', // 要连接的数据库名
  port: '3306', // 数据库端口号
  },
 };

在 vue 中通过 express 连接数据库_第4张图片
3. 在 index.js 中创建一个服务器

// 使用 express 创建服务器
 // 导入 express 模块
 const express = require('express');
 // 调用 express 函数,返回一个数据库实例
 const app = express();
 // 导入路由模块
 const userApi = require('./api/userApi');
 // 端口号
 const port = 8888;
 // 注册全局解析中间件
 app.use(express.json());
 app.use(express.urlencoded({ extended: false }));
 // 注册路由模块
 app.use('/api/user', userApi);
 // 调用 app.listen() 启动服务器
 app.listen(port, () => console.log(`Example app listening on port 8888!`));

在 vue 中通过 express 连接数据库_第5张图片

  1. slqMap.js 写入 sql 语句
// todo sql 语句留后面调用
 module.exports = {
  user: {
  // ? 占位符 后面给数据自动填充
  add: 'insert into test(user\_name, age) values(?, ?)',
  get: 'select \* from test',
  },
 };

在 vue 中通过 express 连接数据库_第6张图片

  1. api/userApi.js 测试用 api 实例
// 测试用 api 实例
 var models = require('../db');
 var express = require('express');
 var router = express.Router();
 var mysql = require('mysql');
 var $sql = require('../sqlMap');
 // 连接数据库
 var conn = mysql.createConnection(models.mysql);
 conn.connect();
 var jsonWrite = (res, ret) => {
  if (typeof ret === 'undefined') {
  res.json({
  code: '1',
  msg: '操作失败',
  });
  } else {
  res.json(ret);
  }
 };
 // 增加用户接口
 // POST 请求
 router.post('/addUser', (req, res) => {
  var sql = $sql.user.add;
  var params = req.body;
  console.log(params);
  // ! [params.username, params.age] 自动填充到之前 ? 里面
  conn.query(sql, [params.user\_name, params.age], (err, result) => {
  if (err) return console.log(err);
  if (result) {
  jsonWrite(res, result);
  }
  });
 });
 // GET 请求
 router.get('/getUser', (req, res) => {
  let sql = $sql.user.get;
  let params = req.query;
  console.log(params);
  conn.query(sql, (err, result) => {
  if (err) {
  console.log(err);
  }
  console.log(res, result);
  });
 });
 module.exports = router;
  1. cmd 或者 PowerShell 打开 server 文件执行 node index

出现这个说明启动成功
image
注意:这里启动后服务器就不要关闭了,不然后面要保错,报这个错启动服务器就行
image

四、编写 vue 测试文件

为了测试方便直接在 HelloWorld.vue 这里面测试

在 vue 中通过 express 连接数据库_第7张图片






五、设置代理与跨域

直接执行 npm run serve 会报错

  1. 这是由于直接访问8080端口,是访问不到的,所以这里需要设置一下代理转发映射.

在 vue 中通过 express 连接数据库_第8张图片

在根目录中创建 vue.config.js 文件,并写入以下内容

具体目录如下:

在 vue 中通过 express 连接数据库_第9张图片

写入内容:

module.exports = {
  devServer: {
  proxy: {
  '/api': {
  target: 'http://127.0.0.1:8888/api',
  changeOrigin: true, // 解决跨域
  pathRewrite: {
  '^/api': '',
  },
  },
  },
  },
 };

在 vue 中通过 express 连接数据库_第10张图片

  1. main.js 中添加
import axios from 'axios';
 Vue.prototype.$http = axios;

在 vue 中通过 express 连接数据库_第11张图片

六、成功页面

完成后关闭编辑器重新打开运行 npm run serve

POST 请求

点击提交

HTML 页面

在 vue 中通过 express 连接数据库_第12张图片

power shell 页面

在 vue 中通过 express 连接数据库_第13张图片

数据库 页面

在 vue 中通过 express 连接数据库_第14张图片

GET 请求

点击获取

HTML和数据库均没有效果

power shell 页面

在 vue 中通过 express 连接数据库_第15张图片

你可能感兴趣的:(在 vue 中通过 express 连接数据库)