最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Custom Express Middleware resulting in TypeError: app.use() requires a middleware function - Stack Overflow

programmeradmin1浏览0评论

const ErrorHandler = (err, req, res, next) => {
    logging.error(err);
    let message = 'An error occured, please try again.';
    let statusCode = 500;

    const response = {
        success: false,
        message: message,
    };

    
    res.status(statusCode).json(response);
    //  in the future add custom error messages based on error type 
};

export default ErrorHandler;

const ErrorHandler = (err, req, res, next) => {
    logging.error(err);
    let message = 'An error occured, please try again.';
    let statusCode = 500;

    const response = {
        success: false,
        message: message,
    };

    
    res.status(statusCode).json(response);
    //  in the future add custom error messages based on error type 
};

export default ErrorHandler;

The above is my custom middleware. I have appropiately imported it on my main app.js file using:

const ErrorHandler = require('./middleware/ErrorHandler');
app.use(ErrorHandler);

And my post route looks like:

router.post('/submit-recipe', getUserMiddleware, upload.any(), async (req, res, next) => {

I have followed along some other posts such as this one, and all my routers are correctly being exported/imported.

Am I missing something obvious here?

Share Improve this question asked Mar 18 at 18:16 Hope Hope 11 6
  • EDIT: I was mixing Common.js exports and ES exports, which was not working... – Hope Commented Mar 18 at 18:37
  • 1 You're mixing ES and CJS modules. require('./middleware/ErrorHandler') is likely an object, this depends on your setup, which the question doesn't mention. Can be fixed with module.exports = ErrorHandler – Estus Flask Commented Mar 18 at 18:39
  • 1 @Hope then you'll want to probably delete your question, since you fixed things yourself mere minutes after asking for help, so you didn't really need help =) – Mike 'Pomax' Kamermans Commented Mar 18 at 19:35
  • I disagree with the commenter above. Since its fine to ask and answer a question yourself if you already know the answer, certainly it is if you figure it out a few minutes after you post the question – Starship Remembers Shadow Commented Mar 18 at 20:09
  • This is my first time actually posting to stack overflow. Can I answer my own questoin? oops – Hope Commented Mar 20 at 13:12
 |  Show 1 more comment

1 Answer 1

Reset to default -1

This can be fixed by changing const ErrorHandler = require('./middleware/ErrorHandler'); to const ErrorHandler = module.exports = ErrorHandler. You seem to have mixed up Common.js exports and ES exports.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论