自定义中间件TypeError:app.use()需要中间件功能

时间:2019-10-30 16:28:49

标签: node.js express middleware

在创建自定义应用程序级别的MiddleWare时,出现了一些错误,下面将与我的代码一起提及。

appErrorHandler.js

let errorHandler  = (err, req, res, next) => {
        console.log("Application Error Handler Middleware is called!");
        console.log(err);
        res.send("Some Error occurred at Global  Level");
    }

    let notFoundHandler = (req, res, next) => {
        console.log("Global Not Found Handler Called");
        res.status(404).send('Route not found in the application');
        next();
    }

    module.exports = {
        errorHandler,
        notFoundHandler
    };

Index.js

const express = require('express');

// Importing middleware
const globalErrorMiddleWare = require('./middleware/appErrorHandler');
const app = express();
app.use(globalErrorMiddleWare.errorHandler);

我遇到错误

PS E:\nodeJs Projects\basicNode> node index.js
./routes/blog.js
E:\nodeJs Projects\basicNode\node_modules\express\lib\application.js:210
    throw new TypeError('app.use() requires a middleware function')     
    ^

TypeError: app.use() requires a middleware function
    at Function.use (E:\nodeJs Projects\basicNode\node_modules\express\lib\application.js:210:11)
    at Object.<anonymous> (E:\nodeJs Projects\basicNode\index.js:39:5)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

0 个答案:

没有答案