|
@@ -0,0 +1,92 @@
|
|
|
+/*
|
|
|
+Nodejs后端MySQL操作接口服务实例
|
|
|
+Version:1.0.0
|
|
|
+Author:shileiye
|
|
|
+Updated:2022.6.7
|
|
|
+
|
|
|
+使用说明
|
|
|
+1、安装依赖:npm install
|
|
|
+2、运行命令:npm run dev
|
|
|
+ 运行命令(效果与上面相同,不需重复执行):node .\server.js
|
|
|
+3、访问地址:http://127.0.0.1:3000/api/index
|
|
|
+*/
|
|
|
+
|
|
|
+var express = require("express"); // 导入express框架
|
|
|
+var mysql = require('mysql'); // 导入MYSQL操作库
|
|
|
+var app = express(); // 生成web服务实例
|
|
|
+app.use(express.json()); // 解析json请求
|
|
|
+app.use(express.urlencoded({ extended: false })); // 解析表单请求
|
|
|
+
|
|
|
+// 配置数据库连接
|
|
|
+const connection = mysql.createConnection({
|
|
|
+ host: '127.0.0.1',
|
|
|
+ user: 'root',
|
|
|
+ password: 'root',
|
|
|
+ database: 'demo'
|
|
|
+});
|
|
|
+
|
|
|
+// 连接数据库
|
|
|
+connection.connect(function (err) {
|
|
|
+ if (err) throw err
|
|
|
+ console.log('mysql 数据库连接成功')
|
|
|
+});
|
|
|
+
|
|
|
+// 查询数据接口
|
|
|
+app.get("/api/index",function(req, res){
|
|
|
+ connection.query('select * from todos',
|
|
|
+ function (error, results, fields) {
|
|
|
+ if (error) throw error;
|
|
|
+ res.send(JSON.stringify(results));
|
|
|
+ console.log(JSON.stringify(results));
|
|
|
+ });
|
|
|
+})
|
|
|
+
|
|
|
+/*
|
|
|
+插入数据接口
|
|
|
+说明:post方式提交body数据,raw填充json数据格式如下:
|
|
|
+{"name": "记录1","description": "记录 1 的描述"}
|
|
|
+*/
|
|
|
+app.post("/api/index",function(req, res){
|
|
|
+ //console.log(req.body);
|
|
|
+ connection.query("INSERT INTO todos SET ? ", req.body,
|
|
|
+ function (error, results, fields) {
|
|
|
+ if (error) throw error;
|
|
|
+ res.send(JSON.stringify("插入记录成功"));
|
|
|
+ console.log("插入记录成功");
|
|
|
+ });
|
|
|
+})
|
|
|
+
|
|
|
+/*
|
|
|
+修改数据接口
|
|
|
+说明:put方式提交body数据,raw填充json数据格式如下:
|
|
|
+{"name": "记录2","description": "记录 2 的描述","id": 1}
|
|
|
+*/
|
|
|
+app.put("/api/index", function(req, res){
|
|
|
+ //console.log(req.body);
|
|
|
+ connection.query('UPDATE `todos` SET `name`=?,`description`=? where `id`=?',
|
|
|
+ [req.body.name, req.body.description, req.body.id],
|
|
|
+ function (error, results, fields) {
|
|
|
+ if (error) throw error;
|
|
|
+ res.send(JSON.stringify("更新记录成功"));
|
|
|
+ console.log("更新记录成功");
|
|
|
+ });
|
|
|
+})
|
|
|
+
|
|
|
+/*
|
|
|
+删除数据接口
|
|
|
+说明:delete方式提交body数据,raw填充json数据格式如下:
|
|
|
+{"id": 1}
|
|
|
+*/
|
|
|
+app.delete("/api/index", function(req, res){
|
|
|
+ //console.log(req.body);
|
|
|
+ connection.query('DELETE FROM todos where id = ?', [req.body.id], (err, result) => {
|
|
|
+ if (err) throw err;
|
|
|
+ res.send(JSON.stringify("删除记录成功"));
|
|
|
+ console.log(result);
|
|
|
+ });
|
|
|
+})
|
|
|
+
|
|
|
+// 启动web服务,端口设置为3000
|
|
|
+app.listen(3000,function(){
|
|
|
+ console.log("服务已启动,监听3000端口,查询接口访问地址:http://127.0.0.1:3000/api/index")
|
|
|
+})
|