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");
});

六、前端请求接口

相关推荐
昂子的博客10 分钟前
Redis缓存 更新策略 双写一致 缓存穿透 击穿 雪崩 解决方案... 一篇文章带你学透
java·数据库·redis·后端·spring·缓存
xixixi7777723 分钟前
了解一下APM工具——就像给软件系统装的“全身CT”,能实时透视从用户点击到后端数据库的每个环节性能,精准定位哪里慢、为什么慢
数据库·安全·数据采集·apm·日志监控
百***416626 分钟前
Java MySQL 连接
java·mysql·adb
q***99439 分钟前
PON架构(全光网络)
网络·数据库·架构
Leon-Ning Liu42 分钟前
Oracle查看正在rebuild online的索引
数据库·oracle
bhots￿43 分钟前
oracle 物化视图设置自动更新日志
数据库·oracle
苦学编程的谢1 小时前
Redis_12_持久化(1)
数据库·redis·缓存
百***46801 小时前
MySQL的底层原理与架构
数据库·mysql·架构
百***12221 小时前
Redis开启远程访问
数据库·redis·缓存
czhc11400756631 小时前
Java1112 基类 c#vscode使用 程序结构
android·java·数据库