您的位置:首页 > 游戏 > 手游 > express连接mysql

express连接mysql

2024/10/6 5:57:53 来源:https://blog.csdn.net/weixin_45580774/article/details/140710711  浏览:    关键词: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");
});

六、前端请求接口

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com