Javascript 类型错误:Router.use() 需要中间件功能但得到了一个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27465850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: Router.use() requires middleware function but got a Object
提问by Datise
There have been some middleware changes on the new version of express and I have made some changes in my code around some of the other posts on this issue but I can't get anything to stick.
新版本的 express 有一些中间件更改,我在我的代码中围绕有关此问题的其他一些帖子进行了一些更改,但我无法坚持下去。
We had it working before hand but I can't remember what the change was.
我们事先就让它工作了,但我不记得有什么变化。
throw new TypeError('Router.use() requires middleware function but got a
^
TypeError: Router.use() requires middleware function but got a Object
node ./bin/www
js-bson: Failed to load c++ bson extension, using pure JS version
js-bson: Failed to load c++ bson extension, using pure JS version
/Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:438
throw new TypeError('Router.use() requires middleware function but got a
^
TypeError: Router.use() requires middleware function but got a Object
at /Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:438:13
at Array.forEach (native)
at Function.use (/Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:436:13)
at /Users/datis/Documents/bb-dashboard/node_modules/express/lib/application.js:188:21
at Array.forEach (native)
at Function.use (/Users/datis/Documents/bb-dashboard/node_modules/express/lib/application.js:185:7)
at Object.<anonymous> (/Users/datis/Documents/bb-dashboard/app.js:46:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
app.js
应用程序.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
var MongoClient = require('mongodb').MongoClient;
var routes = require('./routes/index');
var users = require('./routes/users');
var Users = require('./models/user');
var Items = require('./models/item');
var Store = require('./models/store');
var StoreItem = require('./models/storeitem');
var app = express();
//set mongo db connection
var db = mongoose.connection;
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
// var MONGOHQ_URL="mongodb://localhost:27017/test"
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'something',
resave: true,
saveUninitialized: true
}));
app.use('/', routes);
app.use('/users', users);
app.use(express.static(path.join(__dirname, 'public')));
// catch 404 and forward to error handler
// app.use(function(req, res, next) {
// var err = new Error('Not Found');
// err.status = 404;
// next(err);
// });
// Make our db accessible to our router
app.use(function(req, res, next){
req.db = db;
next();
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
It appears the answer to this question has changed for versioning reasons. Thanks to Nik
由于版本控制的原因,这个问题的答案似乎已经改变。感谢尼克
采纳答案by Rahul Radhakrishnan
If your are using express above 2.x, you have to declare app.router like below code. Please try to replace your code
如果你使用 2.x 以上的 express,你必须像下面的代码一样声明 app.router。请尝试替换您的代码
app.use('/', routes);
with
和
app.use(app.router);
routes.initialize(app);
Please click hereto get more details about app.router
请单击此处获取有关 app.router 的更多详细信息
Thanks
谢谢
Note:
笔记:
app.router is depreciated in express 3.0+. If you are using express 3.0+, refer to Anirudh's answer below.
app.router 在 express 3.0+ 中折旧。如果您使用的是 express 3.0+,请参考下面 Anirudh 的回答。
回答by Anirudh
In any one of your js pages you are missing
在您缺少的任何一个 js 页面中
module.exports = router;
Check and verify all your JS pages
检查并验证您所有的 JS 页面
回答by Parikshit Hooda
Simple solution if your are using express and doing
简单的解决方案,如果您正在使用 express 并且正在做
const router = express.Router();
make sure to
确保
module.exports = router ;
at the end of your page
在您的页面末尾
回答by Michael Staton
I was getting the same error message but had a different issue. Posting for others that are stuck on same.
我收到相同的错误消息,但遇到了不同的问题。为其他卡住的人发帖。
I ported the get, post, put, deletefunctions to new router file while refactoring, and forgot to edit the paths. Example:
我在重构时将get, post, put,delete函数移植到新的路由器文件中,但忘记编辑路径。例子:
Incorrect:
不正确:
//server.js
app.use('/blog-posts', blogPostsRouter);
//routers/blogPostsRouter.js
router.get('/blog-posts', (req, res) => {
res.json(BlogPosts.get());
});
Correct:
正确的:
//server.js
app.use('/blog-posts', blogPostsRouter);
//routers/blogPostsRouter.js
router.get('/', (req, res) => {
res.json(BlogPosts.get());
});
Took a while to spot, as the error had me checking syntax where I might have been wrapping an argument in an object or where I missed the module.exports = router;
花了一段时间才发现,因为错误让我检查语法,我可能已经将参数包装在对象中,或者我错过了 module.exports = router;
回答by Ramesh Sharma
Check your all these file:
检查所有这些文件:
var users = require('./routes/users');
var Users = require('./models/user');
var Items = require('./models/item');
Save properly, In my case, one file was missed and throwing the same error
正确保存,就我而言,丢失了一个文件并抛出了相同的错误
回答by K23raj
check your routes.js file
检查你的 routes.js 文件
example my routes.js
例如我的routes.js
const express = require('express')
const router = express.Router()
const usersController = require('../app/controllers/usersController')
const autheticateuser = require('../app/middlewares/authentication')
router.post('/users/login', autheticateuser, usersController.login)
router.post('/users/register', autheticateuser, usersController.register)
check end of routes.js
检查routes.js的结尾
module.exports = router
module.exports = 路由器
if not there add and module.exports = routerrun again
如果没有添加和module.exports = 路由器再次运行
If your Error is : "TypeError: Route.post()or Route.get()requires middleware function but got a Object"
如果您的错误是:“TypeError: Route.post()或 Route.get()需要中间件功能,但有一个对象”
goto controller.js (i.e., usersController) and check all the function names you might misspelled , or you given in function routes file but missed in contollers
转到 controller.js(即 usersController)并检查所有可能拼写错误的函数名称,或者您在函数路由文件中给出但在控制器中遗漏的函数名称
const User = require('../models/user')
const express = require('express')
const router = express.Router()
module.exports.register = (req, res) => {
const data = req.body
const user = new User(data)
user.save()
.then((user) => {
res.send(user)
})
.catch((err) => {
res.json(err)
})
}
in routes.js i given two routes but in controllers i missed to define route for
在routes.js中,我给出了两条路由,但在控制器中我没有定义路由
router.post('/users/login')
router.post('/用户/登录')
this will make error **
这会出错**
"TypeError: route.post() requires middleware function but got a Object"
“类型错误:route.post() 需要中间件功能,但得到了一个对象”
**
**
回答by Joseph Zapantis
I had this error and solution help which was posted by Anirudh. I built a template for express routing and forgot about this nuance - glad it was an easy fix.
我有 Anirudh 发布的这个错误和解决方案帮助。我为快速路由构建了一个模板,但忘记了这个细微差别 - 很高兴这是一个简单的修复。
I wanted to give a little clarification to his answer on where to put this code by explaining my file structure.
我想通过解释我的文件结构来稍微澄清他关于将代码放在哪里的回答。
My typical file structure is as follows:
我的典型文件结构如下:
/lib
/routes
---index.js(controls the main navigation)
---index.js(控制主导航)
/page-one
/page-two
---index.js
(each file [in my case the index.js within page-two, although page-one would have an index.js too]- for each page - that uses app.METHODor router.METHODneeds to have module.exports = router;at the end)
(每个文件[在我的情况下是第二页中的 index.js,尽管第一页也会有一个 index.js]-对于每个页面-最后使用app.METHOD或router.METHOD需要有module.exports = router;)
If someone wants I will post a link to github template that implements express routing using best practices. let me know
如果有人想要,我将发布一个指向 github 模板的链接,该模板使用最佳实践实现快速路由。让我知道
Thanks Anirudh!!! for the great answer.
谢谢阿尼鲁德!!!对于伟大的答案。

