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
}

后续更新计划

相关推荐
weixin_473894778 分钟前
前端服务器部署分类总结
前端·网络·性能优化
LuckyLay26 分钟前
React百日学习计划-Grok3
前端·学习·react.js
澄江静如练_30 分钟前
小程序 存存上下滑动的页面
前端·javascript·vue.js
2501_9153738831 分钟前
全栈项目实战:Vue3+Node.js开发博客系统
node.js
互联网搬砖老肖1 小时前
Web 架构之会话保持深度解析
前端·架构
菜鸟una1 小时前
【taro3 + vue3 + webpack4】在微信小程序中的请求封装及使用
前端·vue.js·微信小程序·小程序·typescript·taro
hao_04131 小时前
elpis-core: 基于 Koa 实现 web 服务引擎架构设计解析
前端
狂野小青年2 小时前
npm 报错 gyp verb `which` failed Error: not found: python2 解决方案
前端·npm·node.js
鲁鲁5172 小时前
Windows 环境下安装 Node 和 npm
前端·npm·node.js
跑调却靠谱2 小时前
elementUI调整滚动条高度后与固定列冲突问题解决
前端·vue.js·elementui