先在controller/blog.js中定义返回数据的方法:
const getDetail = (id) => { return [ { id: 1, title: '标题a', content: '内容a', createTime: 2324, author: 'zhangsan' } ] }然后暴露出去
module.exports = { getList, getDetail }在在router/blog.js中引入:
const { getList, getDetail } = require('../controller/blog')在在router/blog.js中实现基本逻辑:
if (method === 'GET' && req.path === '/api/blog/detail') { const id = req.query.id const data = getDetail(id) return new SuccessModel(data) }这样get接口就基本实现了。
同理,先在controller/blog.js中定义返回数据的方法:
// 获取新建博客接口 const newBlog = (blogData = {}) => { //blogData是一个博客对象,包含:title content 属性 console.log('newBlog blogData',blogData) return { id : 3 //表示新建博客,插入到数据表里的 id } }然后暴露出去
// 将该函数暴露出去 module.exports = { getList, getDetail, newBlog }在在router/blog.js中引入:
const { getList, getDetail, newBlog } = require('../controller/blog')在router/blog.js实现逻辑:
// 新建一篇博客 if (method === 'POST' && req.path === '/api/blog/new') { const data = newBlog(req.body) return new SuccessModel(data) }跟上边一样,重复代码就不写了~
在controller/blog.js中定义返回数据的方法:
// 获取更新博客接口 const updateBlog = (id, blogData = {}) => { // id 就是更新博客的 id //blogData是一个博客对象,包含:title content 属性 console.log('updateBlog',id,blogData) return true }在router/blog.js实现逻辑:
// 更新博客接口 if (method === 'POST' && req.path === '/api/blog/update') { const result = updateBlog(id, req.body) if (result) { return new SuccessModel() } else { return new ErrorModel('更新博客失败') } }这样更新接口就写完了,我们在postman中发送下post的请求,调用一下:
在controller/blog.js中return 一个 false的时候,后端就返回了更新博客失败:
return true的时候,就返回了更新博客成功(errno:0就是代表成功):
在controller中新建user.js用来返回登录的方法
const loginCheck = (username, password)=> { // 先使用假数据 if (username === "lyb" && password === "123") { return true } return false } module.exports = { loginCheck }然后在router/user.js中实现登录接口逻辑:
导入模块:
const {loginCheck} = require('../controller/user') const { SuccessModel,ErrorModel } =require('../model/resModel')实现逻辑:
const handleUserRouter = (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) if (result) { return new SuccessModel() } return new ErrorModel('登录失败') } } module.exports = handleUserRouternodejs博客项目接口(未连接数据库,未使用登录)
为何将router和controller分开
router:
只管与路由相关的操作、保证数据的正确跟错误的格式是一样的,比如说我们有一个errno的标准,errno为0就是正确,errno为-1就是错误,返回数据有data、errno、mes等信息
controller:
处理数据相关内容、跟路由相关操作没有、来了数据给你处理数据,数据对应的路由跟我没关系
好处:在以后的扩展、构建中清晰,方便!
前端和后端、不同端(子系统)之间对接的一个术语url(路由) /api/blog/list get,输入 输出
API的一部分
后端系统内部的一个模块