1.API对接mysql(博客列表)
controller/blog.js
const {exec} = require('../db/mysql')
// 博客列表处理逻辑
const getList = (author, keyword) => {
let sql = `select * from blog where 1=1 `
if (author) {
sql += `and author='${author}' `
}
if (keyword) {
sql += `and title like %${keyword} `
}
sql += `order by createtime desc;`
// 返回 promise
return exec(sql)
}
- 拼接查询sql语句
- 调用统一执行sql函数,注意其返回的是promise。
router/blog.js
// 获取博客列表
if (method === 'GET' && req.path ==='/api/blog/list') {
// 获取参数
const author = req.query.author || ''
const keyword = req.query.keyword || ''
// 返回的是promise
const result = getList(author, keyword)
return result.then(listData => {
return new SuccessModel(listData)
})
}
- 在获取博客列表路由中调用控制层getList()
- 返回的是promise,需要用then接收。
app.js
// 处理 blog 路由
// 返回的是promise
const blogResult = handleBlogRouter(req,res)
if (blogResult) {
blogResult.then(blogData => {
res.end(
JSON.stringify(blogData)
)
})
return
}