The error you're encountering:
Error: Route.post() requires a callback function but got a [object Undefined]
is due to the Express router expecting a valid callback function for the route, but it's receiving undefined instead. This typically happens when the controller function referenced in the route isn't properly defined or exported. Let's break down the issues and provide steps to resolve them.
1. Missing Export for reviewArticle in adminController.js
In your adminController.js, you’ve defined the reviewArticle function, but it hasn’t been exported. As a result, when you try to reference adminController.reviewArticle in your admin.js routes file, it’s undefined.
Fix: Export reviewArticle
Before Fix (adminController.js):
module.exports = {
// Articles
addArticle,
getAllArticles,
getArticleById,
updateArticle,
deleteArticle,
// News
addNews,
getAllNews,
getNewsById,
updateNews,
deleteNews,
};
After Fix (adminController.js):
module.exports = {
// Articles
addArticle,
getAllArticles,
getArticleById,
updateArticle,
deleteArticle,
// News
addNews,
getAllNews,
getNewsById,
updateNews,
deleteNews,
// Review
reviewArticle, // Added this line
};
Explanation:
By adding reviewArticle to the module.exports object, you ensure that it’s available when you require adminController in your routes.
2. Duplicate Route Definition in admin.js
Looking at your routes/admin.js, you’ve defined the /articles/:id/review POST route twice. Having duplicate routes can cause unexpected behavior and potential conflicts.
Fix: Remove the Duplicate Route
Before Fix (admin.js):
// Reviewers can review articles
router.post(
"/articles/:id/review",
authorizeRoles("reviewer", "admin", "superuser"),
adminController.reviewArticle
);
// ... other routes ...
// Duplicate Route
router.post(
"/articles/:id/review",
authorizeRoles("reviewer", "admin", "superuser"),
adminController.reviewArticle
);
After Fix (admin.js):
// Reviewers can review articles
router.post(
"/articles/:id/review",
authorizeRoles("reviewer", "admin", "superuser"),
adminController.reviewArticle
);
// Removed the duplicate route
Explanation:
Ensure that each route is defined only once to prevent conflicts and ensure clarity in your route definitions.
3. Final adminController.js and admin.js
After applying the fixes, your files should look like the following:
controllers/adminController.js
const Article = require("../models/Article");
const News = require("../models/News");
const { handleControllerError } = require("../utils/errorHandler");
const fs = require("fs");
const path = require("path");
// Helper function to delete files
const deleteFile = (filePath) => {
fs.unlink(path.join(__dirname, "..", filePath), (err) => {
if (err) console.error(`Failed to delete file ${filePath}:`, err);
});
};
// --- Articles CRUD Operations ---
// Create a new article
const addArticle = async (req, res) => {
// ... existing code ...
};
// Get all articles
const getAllArticles = async (req, res) => {
// ... existing code ...
};
// Get a single article by ID
const getArticleById = async (req, res) => {
// ... existing code ...
};
// Update an existing article
const updateArticle = async (req, res) => {
// ... existing code ...
};
// Delete an article
const deleteArticle = async (req, res) => {
// ... existing code ...
};
// Review an article
const reviewArticle = async (req, res) => {
try {
const { id } = req.params;
const { review } = req.body;
const article = await Article.findById(id);
if (!article) {
return res.status(404).json({ message: "Article not found." });
}
// Assuming you have a reviews array in your Article model
article.reviews.push({
reviewer: req.admin._id,
review,
reviewedAt: new Date(),
});
await article.save();
res.status(200).json({ message: "Article reviewed successfully.", article });
} catch (error) {
handleControllerError(error, res, "reviewArticle");
}
};
// --- News CRUD Operations ---
// ... existing news operations ...
module.exports = {
// Articles
addArticle,
getAllArticles,
getArticleById,
updateArticle,
deleteArticle,
// News
addNews,
getAllNews,
getNewsById,
updateNews,
deleteNews,
// Review
reviewArticle, // Ensure this is exported
};
routes/admin.js
const express = require("express");
const router = express.Router();
const adminController = require("../controllers/adminController");
const { verifyToken } = require("../middlewares/auth");
const authorizeRoles = require("../middlewares/authorizeRoles");
const upload = require("../middlewares/upload");
// Protect all admin routes
router.use(verifyToken);
router.use(authorizeRoles("admin", "superuser"));
// --- Article Routes ---
// Publishers can create and update articles
router.post(
"/articles",
authorizeRoles("publisher", "admin", "superuser"),
upload.single("headingImage"),
adminController.addArticle
);
router.put(
"/articles/:id",
authorizeRoles("publisher", "admin", "superuser"),
upload.single("headingImage"),
adminController.updateArticle
);
// SuperUsers and Admins can delete any article
router.delete(
"/articles/:id",
authorizeRoles("admin", "superuser"),
adminController.deleteArticle
);
// Reviewers can review articles
router.post(
"/articles/:id/review",
authorizeRoles("reviewer", "admin", "superuser"),
adminController.reviewArticle
);
// Users can read articles
const readRoles = ["user", "reviewer", "publisher", "admin", "superuser"];
router.get("/articles", authorizeRoles(...readRoles), adminController.getAllArticles);
router.get("/articles/:id", authorizeRoles(...readRoles), adminController.getArticleById);
// --- News Routes ---
// Similar role-based access can be applied to news routes
module.exports = router;
4. Additional Recommendations
-
Consistent Role Authorization: Ensure that roles are consistently authorized across different routes to maintain security and proper access control.
-
Error Handling: Consider enhancing your handleControllerError function to provide more detailed error messages during development, while still maintaining generic messages in production for security.
-
Code Organization: Keep your routes and controllers well-organized, possibly separating them into different files if they grow too large. This improves maintainability and readability.
5. Restart Your Server
After making these changes, ensure you restart your Node.js server to apply the updates:
npm restart
Conclusion
By properly exporting the reviewArticle function and removing the duplicate route definition, you should resolve the Route.post() requires a callback function but got a [object Undefined] error. Always ensure that every controller function used in your routes is correctly exported and that routes are uniquely defined to prevent such issues.