express连接mysql

一、 安装express

npm install express --save

二、express配置

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

三、安装mysql

npm i mysql

四、配置到express中

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请求

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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来到三边坡,努力就发财

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值