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

六、前端请求接口

相关推荐
6+h1 天前
【Redis】数据结构讲解
数据结构·数据库·redis
ID_180079054731 天前
小红书笔记详情 API 接口系列 + 标准 JSON 返回参考(完整版)
数据库·笔记·json
wertyuytrewm1 天前
用Python实现自动化的Web测试(Selenium)
jvm·数据库·python
我真会写代码1 天前
Java事务核心原理与实战避坑指南
java·开发语言·数据库
Gauss松鼠会1 天前
【GaussDB】GaussDB如何创建和管理序列、定时任务
数据库·性能优化·database·gaussdb
Forget_85501 天前
RHEL——NoSQL集群技术
数据库·nosql
wertyuytrewm1 天前
自动化与脚本
jvm·数据库·python
Hello.Reader1 天前
PySpark DataFrame 快速入门创建、查询、分组、读写、SQL 实战一篇讲透
数据库·sql·spark
qq_417695051 天前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
只能是遇见1 天前
ERROR 1524 (HY000) Plugin ‘mysql_native_password‘ is not loaded
android·数据库·mysql