开发博客之数据存储04
程序员文章站
2022-07-03 17:14:37
API对接mysql(博客更新)controller/blog,jsconst updateBlog = (id, blogData = {}) => { const title = blogData.title const content = blogData.content const sql = ` update blog set title='${title}',content='${content}' where id=${id} `...
API对接mysql(博客更新)
controller/blog,js
const updateBlog = (id, blogData = {}) => {
const title = blogData.title
const content = blogData.content
const sql = `
update blog set title='${title}',content='${content}' where id=${id}
`
return exec(sql).then((updateData) => {
console.log('updateData is', updateData)
if (updateData.affectedRows > 0) {
return true
}
return false
})
}
控制台打印:
updateData is OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '(Rows matched: 1 Changed: 1 Warnings: 0',
protocol41: true,
changedRows: 1 }
router/blog.js
// 更新一篇博客
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('更新博客失败')
}
})
}
API对接mysql(博客删除)
controller/blog.js
// 删除博客处理逻辑
const delBlog = (id,author) => {
const sql = `delete from blog where id='${id}' and author='${author}'`
return exec(sql).then((delData) => {
if (delData.affectedRows > 0) {
return true
}
return false
})
router/blog.js
// 删除一篇博客
if (method === 'POST' && req.path ==='/api/blog/delete') {
// 由于还没有登陆,需模拟登陆后
const author = 'zhangsan'
const result = delBlog(id,author)
return result.then(val => {
if (result) {
return new SuccessModel()
} else {
return new ErrorModel('删除博客失败')
}
})
}
API对接mysql(用户登陆)
controller/user.js
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
}
router/user.js
const { loginCheck} = require('../controller/user')
const { SuccessModel, ErrorModel} = require('../model/resModel')
const handleUserBlog = (req, res) => {
const method = req.method //GET/POST
// 登陆
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 = handleUserBlog
app.js
// 处理 user 路由
const userResult = handleUserRouter(req,res)
if (userResult) {
userResult.then(userData => {
res.end(
JSON.stringify(userData)
)
})
return
}
由于返回的是promise,需要对promise进行处理后再使用。
本文地址:https://blog.csdn.net/weixin_44499465/article/details/109004995
上一篇: C语言与Verilog
下一篇: 给我们留点下酒菜行不