01——开发博客项目之接口03

    科技2026-02-02  5

    1.返回模型 2.博客列表接口

    1.返回模型

    文件目录

    model/resModel.js

    class BaseModel { constructor(data, message) { // 兼容只传一个字符串的情况 if (typeof data === 'string') { this.message = data data = null message = null } if (data) { this.data = data } if (message) { this.message = message } } } class SuccessModel extends BaseModel { constructor(data, message) { super(data, message) this.errno = 0 } } class ErrorModel extends BaseModel { constructor(data, message) { super(data, message) this.errno = -1 } } module.exports = { SuccessModel, ErrorModel }

    通过返回模型,我们在返回的时候可以返回下面的格式了,客户端可以通过判断errno的值来判断成功与否,非常方便

    if (blogData) { res.end( // JSON.stringify(blogData) JSON.stringify({ errno: 0, data: {...}, message: '****' }) ) return }

    2.博客列表接口

    获取查询参数 由于博客列表接口需要传入author与keyworld,故需要获取查询参数,由于其他接口也需要,可在app.js中获取。

    app.js

    const querystring = require('querystring') ... // 解析 query req.query = querystring.parse(url.split('?')[1])

    处理博客列表逻辑 controller/blog.js

    const getList = (author, keyword) => { // 先返回假数据(格式正确) return [ { id: 1, title: '标题A', content: '内容A', createTime: 1602154489614, author: 'zhangshan' }, { id: 2, title: '标题B', content: '内容B', createTime: 1602154489714, author: 'lisi' } ] } module.exports = { getList }

    路由中使用博客列表逻辑

    const { getList } = require('../controller/blog') const { SuccessModel, ErrorModel} = require('../model/resModel') const handleBlogRouter = (req, res) => { const method = req.method //GET/POST // 获取博客列表 if (method === 'GET' && req.path ==='/api/blog/list') { // 获取参数 const author = req.query.author || '' const keyword = req.query.keyword || '' const listData = getList(author, keyword) return new SuccessModel(listData) } // 获取博客详情 if (method === 'GET' && req.path ==='/api/blog/detail') { return { msg: '这是获取博客详情的接口' } } // 新建一篇博客 if (method === 'POST' && req.path ==='/api/blog/new') { return { msg: '这是新建博客的接口' } } // 更新一篇博客 if (method === 'POST' && req.path ==='/api/blog/update') { return { msg: '这是更新博客的接口' } } // 删除一篇博客 if (method === 'POST' && req.path ==='/api/blog/delete') { return { msg: '这是删除博客的接口' } } } module.exports = handleBlogRouter 获取查询参数引入博客列表逻辑,以查询参数作为参数调用引入返回模型,以返回模型格式返回数据
    Processed: 0.034, SQL: 11