【发布时间】:2022-07-14 11:52:05
【问题描述】:
我正在构建一个使用 MVC 结构的节点应用程序。由于我没有使用 MVC 结构的经验,因此无法有效地将中间件放置在此架构中的位置。 结构概览:-
//User routes
router.get('/fetchAllCourses/:schoolId', courseController.apiFetchCourses);
//Controller
const courseServices = require('../services/courseService');
const courseCtrl = {};
courseCtrl.apiFetchCourses = async (req, res, next) => {
try {
const schoolId = req.params.schoolId;
const fetchedCourses = await courseServices.fetchCourses(schoolId);
!fetchedCourses ? res.status(404).send('School fetch error') :
res.send(fetchedCourses);
} catch (error) {
res.status(500).send('some error occured,' + error.message);
}
}
module.exprots = courseCtrl;
//services
const courses = require('../models/Course'),
const courseService = {};
courseService.fetchCourses = async (schoolId) => {
try {
const foundSchool = await schools.findById(schoolId).populate('course');
if (!foundSchool) return console.log('School search error');
return foundSchool.course;
} catch (error) {
console.log(`Course fetch error: ${error}`)
}
};
module.exports = courseServices;
我有一个中间件,它验证来自客户端的身份验证令牌,并在验证后将请求正文传递给控制器。但是我在放置我的中间件时遇到了麻烦。
【问题讨论】:
标签: node.js api express routes mern