个人简介
👀个人主页: 前端杂货铺 🙋?♂?学习方向: 主攻前端方向,也会涉及到服务端 📃个人状态: 在校大学生一枚,已拿多个前端 offer(秋招) 🚀未来打算: 为中国的工业软件事业效力n年 🥇推荐学习:🍍前端面试宝典 🍉Vue2 🍋Vue3 🍓Vue2&Vue3项目实战 🥝Node.js 🌕个人推广:每篇文章最下方都有加入方式,旨在交流学习&资源分享,快加入进来吧
Node.js系列文章目录
一、前言
前面我们已经使用了 假数据去处理路由接口,并学习了开发博客路由相关 MySQL的基础知识。
下面我们就可以 整合改进 这两部分,实现 API 和 MySQL 的对接 工作。
二、Node.js 连接 MySQL
安装 MySQL
npm install mysql

在 src 目录下创建 ./conf/db.js 文件,用于连接数据库的配置

db.js 文件
- 线上环境与开发环境的配置是不一样的
- 这里写的是一样的,因为项目没有上线
const env = process.env.NODE_ENV
let MYSQL_CONF
if (env === 'dev') {
MYSQL_CONF = {
host: 'localhost',
user: 'root',
password: '1234abcd',
port: '3306',
database: 'myblog'
}
}
if (env === 'production') {
MYSQL_CONF = {
host: 'localhost',
user: 'root',
password: '1234abcd',
port: '3306',
database: 'myblog'
}
}
module.exports = {
MYSQL_CONF
}
在 src 目录下创建 ./db/mysql.js 文件,用于存放一些数据

mysql.js 文件
- 引入 mysql 和连接数据库
- 封装 sql 函数,用于统一执行
const mysql = require('mysql')
const { MYSQL_CONF } = require('../conf/db')
const con = mysql.createConnection(MYSQL_CONF)
con.connect()
function exec(sql) {
const promise = new Promise((resolve, reject) => {
con.query(sql, (err, result) => {
if (err) {
reject(err)
return
}
resolve(result)
})
})
return promise
}
module.exports = {
exec
}
三、API 对接 MySQL
1、文件目录

2、控制器_controller
blog.js 文件
- blog 相关 sql 逻辑
- 返回的是 promise 实例
const { exec } = require('../db/mysql')
const getList = (author, keyword) => {
let sql = `select * from blogs where 1=1 `
if (author) {
sql += `and author='${author}' `
}
if (keyword) {
sql += `and title like '%${keyword}%' `
}
sql += `order by createtime desc;`
return exec(sql)
}
const getDetail = (id) => {
const sql = `select * from blogs where id='${id}'`
return exec(sql).then(rows => {
return rows[0]
})
}
const newBlog = (blogData = {}) => {
const title = blogData.title
const content = blogData.content
const author = blogData.author
const createTime = Date.now()
const sql = `
insert into blogs (title, content, createtime, author)
values ('${title}', '${content}', '${createTime}', '${author}');
`
return exec(sql).then(insertData => {
console.log('insertData is ', insertData)
return {
id: insertData.insertId
}
})
}
const updateBlog = (id, blogData = {}) => {
const title = blogData.title
const content = blogData.content
const sql = `
update blogs set title='${title}', content='${content}' where id=${id}
`
return exec(sql).then(updateData => {
if (updateData.affectedRows > 0) {
return true
}
return false
})
}
const delBlog = (id, author) => {
const sql = `delete from blogs where id='${id}' and author='${author}'`
return exec(sql).then(delData => {
if (delData.affectedRows > 0) {
return true
}
return false
})
}
module.exports = {
getList,
getDetail,
newBlog,
updateBlog,
delBlog
}
user.js 文件
- 登录相关 sql 逻辑
- 返回的是 promise 实例
const { exec } = require('../db/mysql')
const loginCheck = (username, password) => {
const sql = `
select username, realname from users where username='${username}' and password='${password}'
`
return exec(sql).then(rows => {
return rows[0] || {}
})
}
module.exports = {
loginCheck
}
3、路由_router
blog.js 文件
const { getList, getDetail, newBlog, updateBlog, delBlog } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const handleBlogRouter = (req, res) => {
const method = req.method
const id = req.query.id
if (method === 'GET' && req.path === '/api/blog/list') {
const author = req.query.author || ''
const keyword = req.query.keyword || ''
const result = getList(author, keyword)
return result.then(listData => {
return new SuccessModel(listData)
})
}
if (method === 'GET' && req.path === '/api/blog/detail') {
const result = getDetail(id)
return result.then(data => {
return new SuccessModel(data)
})
}
if (method === 'POST' && req.path === '/api/blog/new') {
req.body.author = 'zhangsan'
const result = newBlog(req.body)
return result.then(data => {
return new SuccessModel(data)
})
}
if (method === 'POST' && req.path === '/api/blog/update') {
const result = updateBlog(id, req.body)
return result.then(val => {
if (val) {
return new SuccessModel()
} else {
return new ErrorModel('更新博客失败')
}
})
}
if (method === 'POST' && req.path === '/api/blog/del') {
const author = 'zhangsan'
const result = delBlog(id, author)
return result.then(val => {
if (val) {
return new SuccessModel()
} else {
return new ErrorModel('删除博客失败')
}
})
}
}
module.exports = handleBlogRouter
user.js 文件
const { loginCheck } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const handleUserRouter = (req, res) => {
const method = req.method
if (method === 'POST' && req.path === '/api/user/login') {
const { username, password } = req.body
const result = loginCheck(username, password)
return result.then(data => {
if (data.username) {
return new SuccessModel()
}
return new ErrorModel('登录失败')
})
}
}
module.exports = handleUserRouter
四、各个接口的测试
查询博客列表

通过关键字查询博客(模糊查询)

通过关键字查询博客(精准查询)

通过id获取博客详情

通过 ApiPost/Postman 工具测试 新建博客


通过 ApiPost/Postman 工具测试 更新博客



通过 ApiPost/Postman 工具测试 删除博客


通过 ApiPost/Postman 工具测试 登录

四、写在最后(附源码)
至此,开发博客的项目(API 对接 MySQL)就完成了。
后续会对该项目进行多次重构【多种框架(express,koa)和数据库(mysql,sequelize,mongodb)】
如果你需要该项目的 源码,请通过本篇文章最下面的方式 加入 进来~~

|