本文介绍了类型错误:Router.use() 需要一个中间件函数,但有一个未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 NODEJS 的初学者,我正在尝试做小型聊天应用程序.我在 server.js 中遇到路由问题. [ 在 app.use('/',chatcat.router);].我附上了下面的错误.谁能告诉我?.如何解决这个问题.提前致谢...

Everyone I'm beginner in NODEJS I'm trying to do small chat app.I'm facing routing problem in server.js. [ in the line app.use('/',chatcat.router); ].I have attached the error below. Can anyone tell me?.how to resolve this problem. Thanks in advance...

server.js

const express=require('express');

const app=express();

const chatcat=require('./app');

app.set('port',process.env.PORT || 8086);

app.use(express.static('public'));

app.set('view engine','ejs');

app.use('/',chatcat.router);

app.listen(app.get('port'),()=>{
    console.log('server is listening on port: ',app.get('port'));
});

app/index.js

app/index.js

const routes=require('./routes');

module.exports={
     router: routes()
}

app/routes/index.js:

app/routes/index.js:

'use strict';

const h=require('../helpers');

console.log('routers/index outside');

module.exports=()=>{

    console.log('routers/index inside');

    let routes={

        'get':{
            '/':(req,res,next)=>{
                res.render('login');
            },
            '/chat':(req,res,next)=>{
                res.render('chatroom');
            },
            '/rooms':(req,res,next)=>{
                res.render('rooms');
            }
        } ,
        'post':{
            '/chat':(req,res,next)=>{
              res.render('chatroom');
            }
        }
    }

    return h.route12(routes);
};

app/helpers/index.js

app/helpers/index.js

'use strict';

const express=require('express');

const router=express.Router();

console.log('helpers/index outside');
let _registerRoutes=(routes,method)=>{

    for(let key in routes){
        if( (typeof routes[key] === 'object') && (routes[key] !==null) && !( routes[key] instanceof Array)){

            _registerRoutes(routes[key],key);
        }
        else{
            if(method === 'get'){
                console.log('get in');
                router.get(key,routes[key]);
            }
            else if(method ==='post'){
                console.log('post in');
                router.post(key,routes[key]);
            }
        }
    }
}

let route12=routes=>{
    console.log('calling registerroutes');
    _registerRoutes(routes);
}

module.exports={
    route12
}

我收到如下错误:

E:\STUDIES\Node Technologies\NodeJS\chatcat\node_modules\express\lib\router\index.js:458throw new TypeError('Router.use() 需要一个中间件函数,但得到了一个 ' + gettype(fn))^

E:\STUDIES\Node Technologies\NodeJS\chatcat\node_modules\express\lib\router\index.js:458 throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) ^

TypeError:Router.use() 需要一个中间件函数,但得到了一个 undefined在 Function.use (E:\STUDIES\Node Technologies\All about NodeJS\chatcat\node_modules\express\lib\router\index.js:458:13)在功能.(E:\STUDIES\Node Technologies\All about NodeJS\chatcat\node_modules\express\lib\application.js:220:21)在 Array.forEach()在 Function.use (E:\STUDIES\Node Technologies\All about NodeJS\chatcat\node_modules\express\lib\application.js:217:7)在对象.(E:\STUDIES\Node Technologies\All about NodeJS\chatcat\server.js:13:5)在 Module._compile (module.js:653:30)在 Object.Module._extensions..js (module.js:664:10)在 Module.load (module.js:566:32)在 tryModuleLoad (module.js:506:12)在 Function.Module._load (module.js:498:3)

TypeError: Router.use() requires a middleware function but got a undefined at Function.use (E:\STUDIES\Node Technologies\All about NodeJS\chatcat\node_modules\express\lib\router\index.js:458:13) at Function. (E:\STUDIES\Node Technologies\All about NodeJS\chatcat\node_modules\express\lib\application.js:220:21) at Array.forEach () at Function.use (E:\STUDIES\Node Technologies\All about NodeJS\chatcat\node_modules\express\lib\application.js:217:7) at Object. (E:\STUDIES\Node Technologies\All about NodeJS\chatcat\server.js:13:5) at Module._compile (module.js:653:30) at Object.Module._extensions..js (module.js:664:10) at Module.load (module.js:566:32) at tryModuleLoad (module.js:506:12) at Function.Module._load (module.js:498:3)

推荐答案

让我们一步一步往回走:

Let's take this step by step going backwards:

在这一行:

app.use('/',chatcat.router);

您收到一个错误,指出 chatcat.router 在它应该是一个函数时未定义.变量 chatcat 来自于:

You get an error that says chatcat.router is undefined when it's supposed to be a function. The variable chatcat comes from this:

const chatcat=require('./app');

所以,在 app/index.js 中,你有这个:

So, in app/index.js, you have this:

const routes=require('./routes');

module.exports={
     router: routes()
}

所以,这意味着您正在调用 require('./routes'); 应该返回的函数并将其返回值放入导出中.

So, that means you're calling the function that require('./routes'); is supposed to return and putting its return value in the exports.

当我们查看 app/routes/index.js 时,我们看到您正在导出一个函数,该函数在调用时返回:

When, we go look in app/routes/index.js, we see that you're exporting a function that when called returns this:

return h.route12(routes);

h 从何而来:

const h=require('../helpers');

当我们查看 app/helpers/index.js 时,我们看到它正在导出 route12 函数:

When we go look in app/helpers/index.js, we see that it's exporting the route12 function:

let route12=routes=>{
    console.log('calling registerroutes');
    _registerRoutes(routes);
}

module.exports={
    route12
}

而且,您可以看到 route12() 在调用时不返回任何内容.

And, you can see that route12() when called doesn't return anything.

因此你最终得到 undefined.

因此,快速而肮脏的解决方法是让 route12() 返回一个函数,该函数是您想要的中间件函数.

So, the quick and dirty fix is to make route12() return a function that is whatever you want the middleware function to be.

但是,老实说这段代码很乱.看看仅仅为了找出 chatcat.router 实际应该是什么就需要做多少工作.应该没有这么难.您在顶级导入和实际实现之间放置了一大堆中间文件,所有这些层都没有增加任何价值.他们所做的只是晦涩难懂的事情.而且,由于这是一个中间件功能,因此您不会在很多其他地方使用相同的中间件功能.

But, honestly this code is a pretty messy. Look at how much work it was just to find out what chatcat.router is actually supposed to be. It shouldn't be this difficult. You've put a whole bunch of intermediate files in between the top level import and the actual implementation and all those layers don't add any value. All they do is obscure things. And, since this is a middleware function, it's not like you're going to be using this same middleware function lots of other places.

有很多不同的方法可以清理它,但我建议将中间件函数放在它自己的模块中,然后直接将它require().如果中间件功能需要访问其他功能,那么让它require()在它需要的地方.模块化通常应尽可能浅.您不必遵循一系列不会增加任何价值的必需模块来实现实际实现.

There are many different ways you could clean this up, but I'd suggest putting the middleware function in its own module and require() it in directly. If the middleware function needs access to other functionality, then let it require() in what it needs. Modularity should generally be as shallow as possible. You shouldn't have to follow through a chain of required modules that don't add any value to get to the actual implementation.

这里似乎也存在概念问题.app.use() 应该用于安装中间件(参与处理传入请求的请求处理程序).但是,您的 route12() 不仅没有返回任何可以用作中间件的东西,这甚至看起来不像它的生活目的.当我们查看 _registerRoutes() 时,看起来您正在尝试重新实现 Express 已经为您提供的功能,但它看起来像是一个错误的实现,因为您假设它传递了第二个参数 method 你自己的代码没有传递给它,然后它里面的代码试图把东西放在一个永远不会连接到你的应用程序的 router 上.

There also appears to be a conceptual problem here. app.use() should be used to install middleware (request handlers that participate in the handling of incoming requests). But, not only does your route12() not return anything that could be used as middleware, that doesn't even look like it's purpose in life. When we look at _registerRoutes() it looks like you're trying to reimplement functionality that Express already offers you, but it looks like a wrong implementation because you're assuming that it gets passed a second argument method which your own code does not pass to it and then code inside it is attempting to put things on a router which is never hooked up to your app.

总的来说,可能有一种非常简单的方法来完成您想要做的任何事情.此处并没有真正描述您想要完成的具体工作,而且实施已经足够离谱,我无法完全确定您打算做什么以了解如何建议简化.

Overall, there is likely a massively simpler way to do whatever it is you're trying to do. What exactly you're trying to accomplish isn't really described here and the implementation is enough off-base that I can't quite tell what you intended to do to know how to suggest a simplification.

无论如何,我已经向您解释了为什么您会收到原始错误.希望你能从那里得到它并修复/简化.

Anyway, I've explained to you why you got your original error. Hopefully you can take it from there and fix/simplify.

这篇关于类型错误:Router.use() 需要一个中间件函数,但有一个未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 13:42
查看更多