express连接mysql

一、 安装express

bash 复制代码
npm install express --save

二、express配置

bash 复制代码
//引入
const express = require("express");
//创建实例
const app = express();
//启动服务
app.listen(8081, () => {
  console.log("http://localhost:8081");
});

三、安装mysql

bash 复制代码
npm i mysql

四、配置到express中

bash 复制代码
const express = require("express");
const mysql = require("mysql"); //引入mysql
const app = express();
// 设置MySQL连接配置
const connection = mysql.createConnection({
  host: "localhost", 
  user: "root",  //数据库账号
  password: "root", //数据库密码
  database: "deli", //数据库名称
});
// 连接到MySQL数据库
connection.connect((error) => {
  if (error) throw error;
  //连接成功打印结果`如果连接失败,记得查看数据库是否开启`
  console.log("Successfully connected to the database.");
});
app.listen(8081, () => {
  console.log("http://localhost:8081");
});

五、加入get请求

bash 复制代码
const express = require("express");
const mysql = require("mysql");
const app = express();
// 设置MySQL连接配置
const connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "root",
  database: "deli",
});
// 连接到MySQL数据库
connection.connect((error) => {
  if (error) throw error;
  console.log("Successfully connected to the database.");
});


`这里为增加的get请求内容`
app.get("/testApi", (req, res) => {
  //获取到请求参数
  const { config_name } = req.query;
  //去表名称为config的表中去查数据 ,查询条件为`config_name="${config_name}"`,其中双引号不可省去
  connection.query(
    `SELECT * FROM config  where config_name="${config_name}"`,
    (error, results, fields) => {
      if (error) throw error;
      // 发送响应
      res.send(results);
    }
  );
});

app.listen(8081, () => {
  console.log("http://localhost:8081");
});

六、前端请求接口

相关推荐
程序员Android几秒前
MTK多帧拍照流程分析
数据库
不剪发的Tony老师2 分钟前
Apache Doris:一款高性能的实时数据仓库
数据库·数据仓库
甜可儿13 分钟前
redis序列化设置
数据库·redis
GGBondlctrl18 分钟前
【SpringBoot】论坛项目中如何进行实现发布文章,以及更新对应数据库的数据更新
数据库·springboot项目·三层设计思想·文章发布项目
若云止水32 分钟前
Ubuntu 下 nginx-1.24.0 源码分析 - ngx_init_cycle 函数 - 详解(4)
数据库·nginx·ubuntu
jay丿1 小时前
Django模板系统深入
数据库·django·sqlite
千层冷面1 小时前
Redis除了做缓存还能做什么?
数据库·redis·缓存
码有余悸3 小时前
Redis:高性能的键值存储系统
数据库·redis·缓存
剑客狼心7 小时前
Oracle:什么是存储过程
数据库·oracle
小王努力学编程7 小时前
【MySQL篇】表的操作
数据库·mysql