Nodejs 第三十七章(mysql2)

在之前的篇章中,已经补充完成mysql的基本知识,那么现在开始,我们需要把mysqlexpress,nodejs连接起来。

安装依赖

sh 复制代码
npm install mysql2 express js-yaml
  1. mysql2 用来连接mysql和编写sq语句
  2. express 用来提供接口 增删改差
  3. js-yaml 用来编写配置文件

编写代码

db.ocnfig.yaml

yaml 复制代码
db:
   host: localhost #主机
   port: 3306 #端口
   user: root #账号
   password: '123456' #密码 一定要字符串
   database: xiaoman # 库

index.js

js 复制代码
import mysql2 from 'mysql2/promise';
import express from 'express';
import jsYaml from 'js-yaml'
import fs from 'node:fs'
const yamlInfo = fs.readFileSync('./db.config.yaml')
const config = jsYaml.load(yamlInfo)
const sql = await mysql2.createConnection({
    ...config.db
});

const app = express();
app.use(express.json());
//查询全部
app.get('/', async (req, res) => {
    const [rows] = await sql.query('select * from user');
    res.send(rows)
})
//单个查询
app.get('/user/:id', async (req, res) => {
    const [rows] = await sql.query('select * from user where id = ?', [req.params.id]);
    res.send(rows)
})
//创建
app.post('/create', async (req, res) => {
    const { name, age, hobby } = req.body;
    const [rows] = await sql.query('insert into user (name, age, hobby) values (?, ?, ?)', [name, age, hobby]);
    res.send(rows)
})
//更新
app.post('/update', async (req, res) => {
    const { id, name, age, hobby } = req.body;
    const [rows] = await sql.query('update user set name = ?, age = ?,hobby = ? where id = ?', [name, age, hobby, id]);
    res.send(rows)
})


const port = 3000;
app.listen(port, () => {
    console.log(`server is running at http://localhost:${port}`);
})

index.http

方便测试接口

http 复制代码
# 查询全部
 GET http://localhost:3000/ HTTP/1.1

# 单个查询
GET http://localhost:3000/user/2 HTTP/1.1

# 添加数据
POST http://localhost:3000/create HTTP/1.1
Content-Type: application/json

{
    "name":"张三",
    "age":18
}

# 更新数据
POST http://localhost:3000/update HTTP/1.1
Content-Type: application/json

{
    "name":"法外狂徒",
    "age":20,
    "id":23
}

后续更新计划

相关推荐
Nayana1 小时前
前端控制批量请求并发
前端
ssjlincgavw1 小时前
前端高手进阶:从十万到千万,我的性能优化终极指南(实战篇)
前端
比老马还六1 小时前
Bipes项目二次开发/设置功能-1(五)
前端·javascript
转转技术团队1 小时前
VDOM 编年史
前端·设计模式·前端框架
蓝瑟忧伤1 小时前
前端性能体系的全面升级:现代 Web 如何构建可量化、可治理、可演进的性能架构?
前端·架构
申阳1 小时前
Day 17:03. 基于 Tauri 2.0 开发后台管理系统-登录页面开发
前端·后端·程序员
诸葛亮的芭蕉扇2 小时前
tree组件点击节点间隙的异常问题分析
前端·javascript·vue.js
GinoWi2 小时前
HTML基本格式 - 第一个HTML网页
前端
顶鲜花的牛粪2 小时前
Astro 项目升级全栈:EdgeOne Pages 部署指南
前端
0***R5152 小时前
前端云原生
前端·云原生