后端报错‘Route.post() requires a callback function but got a [object Undefined]’原因排查
错误原因排查与修复
当前报错 Error: Route.post() requires a callback function but got a [object Undefined] 的核心原因是:POST路由的回调参数中存在undefined值,结合你的代码,主要有以下几个问题需要修复:
1. 控制器导出方式错误,导致函数未完整导出
你的控制器代码中,先用exports.sendStripeApiKey定义了一个导出,随后又用module.exports = {processPayment}覆盖了整个导出对象,这会导致sendStripeApiKey没有被包含在最终导出内容里。虽然当前报错指向POST路由,但这个错误会导致后续GET路由的sendStripeApiKey同样为undefined,触发同类问题。
修复方法:统一用module.exports导出两个函数
const catchAsyncErrors = require("../middleware/catchAsyncError"); const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY); const processPayment = catchAsyncErrors(async (req, res, next) => { const myPayment = await stripe.paymentIntents.create({ amount: req.body.amount, currency: "inr", metadata: { company: "Zebrow", }, }); res.status(200).json({ success: true, client_secret: myPayment.client_secret }); }); const sendStripeApiKey = catchAsyncErrors(async (req, res, next) => { res.status(200).json({ stripeApiKey: process.env.STRIPE_API_KEY }); }); // 统一导出两个函数,避免覆盖 module.exports = { processPayment, sendStripeApiKey };
2. 检查isAuthenticatedUser中间件的导出是否正确
路由中导入的isAuthenticatedUser如果在../middleware/auth文件中没有正确导出,会导致它变为undefined,直接触发POST路由的回调错误。
检查auth.js文件的导出逻辑,确保格式正确:
// 示例正确导出方式 exports.isAuthenticatedUser = (req, res, next) => { // 你的中间件逻辑 next(); }; // 或者用对象形式导出 module.exports = { isAuthenticatedUser };
3. 验证catchAsyncErrors中间件的实现
如果以上修复后仍报错,检查catchAsyncErrors是否为正确的高阶函数,确保它能返回一个可执行的回调函数。正确的实现应该是:
// 正确的catchAsyncErrors示例 module.exports = (func) => (req, res, next) => { Promise.resolve(func(req, res, next)).catch(next); };
内容的提问来源于stack exchange,提问作者Vaishali
相关产品推荐
相关产品推荐

