node开发:连接mysql数据库进行get、post操作

2023-06-0817:01:54WEB前端开发Comments927 views字数 4077阅读模式

一、介绍

  • 前端 javascript
    • 三大核心
      • ECMAScript
      • DOM
      • BOM
    • 操作内容
      • 浏览器
      • 解决兼容问题
  • 后端 javascript (node)
    • 核心
      • ECMAScript
    • 操作内容
      • 后端代码
      • 数据库

二、环境

node:下载 | Node.js (nodejs.org)
mysql:MySQL :: Download MySQL Installer文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

注意安装MySQL时请选择下图选项

因为mysql 8加密规则是mysql_native_password,而在之后版本,加密规则是caching_sha2_password ,node不支持mysql 8,连接时会报如下错误文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
node开发:连接mysql数据库进行get、post操作
e9713c38e6cf9b05d175c7d6fbb8ef9.png

三、node连接数据库

3.1入口文件 index.js文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

安装引入express
npm install express
const express = require("express");
const app = express();
const router = require("./route/index");
app.use(router);

const port = 9999;
app.listen(port, function () {
  console.log("访问地址 http://localhost:" + port);
});

3.2创建连接 db/index.js
3.2.1安装引用mysql文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

npm install mysql
const mysql = require("mysql");
// 配置
const config = {
  host: "127.0.0.1", //服务地址
  port: 3306, // MySQL数据库端口号
  database: "node", //数据库名
  user: "root", //连接数据库的用户名
  password: "123456", //连接数据库的密码
};

// 第一种
const connection = mysql.createConnection(config);
// 第二种
const pool = mysql.createPool(config);

module.exports = pool;

3.2.2连接数据库的两种方法区别文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

配置

const config = {
host: "127.0.0.1", //服务地址
port: 3306, // MySQL数据库端口号
database: "node", //数据库名
user: "root", //连接数据库的用户名
password: "123456", //连接数据库的密码
};文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

1、mysql.createConnection(config);

这种方法较为底层,且每次操作数据库都需要新建数据库连接,若数据库操作需求多,对服务器消耗较大文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

2、mysql.createPool(config);

数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏。
通俗的理解就是: 数据库连接池是程序启动时建立足够数量的数据库连接对象,并将这些连接对象组成一个池,由程序动态的对池中的连接对象进行申请、使用和释放。
优点
1.避免应用程序频繁的连接、断开数据库
2.提供数据库连接对象的使用频率。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

3.3路由文件 route/index.js
3.3.1连接数据库使用get方法并做查询操作文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

const express = require("express");
const router = express.Router();
const db = require("../db/index");

router.get("/getUserByName", function (req, res) {
  const { name } = req.query; // 接收参数
  const sql = "select * from user where name='" + name + "'";

  if (!name) {
    return res.json({ code: 1002, message: "缺少参数name" });
  }

  // mysql.createConnection(config);对应的连接查询方法
  // db.connect();
  // db.query(sql, function (err, result) {
  //   if (!err) {
  //     res.send(result);
  //   } else {
  //     console.log("数据库连接失败");
  //   }
  //   db.end(); // 终止连接
  // });

  // mysql.createPool(config);对应的连接查询方法
  db.getConnection(function (err, conn) {
    conn.connect(function (err) {
      conn.query(sql, function (err, result) {
        if (!err) {
          res.json(result);
        } else {
          console.log("数据库连接失败");
        }
      });
      conn.release(); // 释放连接池,等待别的连接池使用
    });
  });
});
module.exports = router;

3.3.2使用post方式进行数据修改文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

post接受其参数方法

1、使用express内置方法
express.json()函数是Express中的内置中间件函数。它使用body-parser解析带有JSON有效负载的传入请求。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

const express = require("express");
const router = express.Router();
const parser = express.json();

// 使用json格式传参
router.post("/edit", parser, function (req, res) {
  console.log(req.body);
});

2、使用body-parser文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

//安装body-parser
npm install body-parser
const bodyparser = require("body-parser");
// 以解析表单提交数据为例 application/x-www-form-urlencoded
// extended: false 值是false时解析值是“String”或“Array” 值是true的时候可以解析任意类型的数据
const parser = bodyparser.urlencoded({ extended: false });
router.post("/edit", parser, function (req, res) {
  console.log(req.body);
});

此处使用body-parser方式接收参数文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

const express = require("express");
const router = express.Router();
const db = require("../db/index");

const bodyparser = require("body-parser");
// 以解析表单提交数据为例 application/x-www-form-urlencoded
// extended: false 值是false时解析值是“String”或“Array” 值是true的时候可以解析任意类型的数据 
const parser = bodyparser.urlencoded({ extended: false });

router.post("/edit", parser, function (req, res) {
  console.log(req.body.id);
});
module.exports = router;
示例
const express = require("express");
const router = express.Router();
const db = require("../db/index");
const bodyparser = require("body-parser");
// 以解析表单提交数据为例 application/x-www-form-urlencoded
// extended: false 值是false时解析值是“String”或“Array” 值是true的时候可以解析任意类型的数据
const parser = bodyparser.urlencoded({ extended: false });

router.post("/edit", parser, function (req, res) {
  const { id, age } = req.body;
  const sql = `update user set age=${age} where id=${id}`;
  if (!age) {
    return res.json({ code: 1002, message: "缺少参数age" });
  }
  if (!id) {
    return res.json({ code: 1002, message: "缺少参数id" });
  }
  db.getConnection(function (err, conn) {
    conn.connect(function (err) {
      conn.query(sql, function (err, result) {
        if (!err) {
          res.json({ code: 200, message: "修改成功" });
        } else {
          console.log("数据库连接失败");
        }
      });
      conn.release();
    });
  });
});

module.exports = router;

四、处理前端请求跨域

使用cors解决前端请求跨域问题文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

npm i cors -s

使用方法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html

const express = require("express");
const app = express();
app.use(cors())
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/46026.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/46026.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定