Javascript 快速错误 - TypeError:Router.use() 需要中间件函数但得到了一个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29941208/
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
Express error - TypeError: Router.use() requires middleware function but got a Object
提问by MattClaff
I am getting this error when I run npm start to run my express app.
当我运行 npm start 来运行我的 express 应用程序时,我收到了这个错误。
TypeError: Router.use() requires middleware function but got a Object
my app.jscode
我的app.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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// 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: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// 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;
my index.jscode
我的index.js代码
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
/* GET Hello World page. */
router.get('/helloworld', function(req, res) {
res.render('helloworld', { title: 'Hello, World!' })
});
module.exports = router;
I am quirte new to using Node and express. I cant see where I have gone wrong. Can anybody see what my problem is?
我对使用 Node 和 express 很陌生。我看不出我哪里出错了。任何人都可以看到我的问题是什么?
回答by HPierce
I found the answer in the comments from Kop4lyf:
我在Kop4lyf的评论中找到了答案:
check your users.js. It should also be exporting the router like index.js, if you can try that.
检查您的 users.js。如果您可以尝试,它也应该像 index.js 一样导出路由器。
However, this question was my top search result when I ran into this issue, so I am promoting to an answer.
然而,当我遇到这个问题时,这个问题是我的最佳搜索结果,所以我正在推广一个答案。
The error is caused because one of your route modules is not being exported - meaning Express does not have access to it when it tries to identify all of your routes.
该错误是因为您的路由模块之一未导出 - 这意味着 Express 在尝试识别您的所有路由时无法访问它。
You can fix this by adding module.exports = router;to the end of each of your route files.
您可以通过添加module.exports = router;到每个路由文件的末尾来解决此问题。
Example:
例子:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
//Do whatever...
});
module.exports = router;
More information about module.exportscan be found on this questionor the offcial Node.js documentation.
module.exports可以在此问题或官方 Node.js 文档中找到有关更多信息。
回答by SUBHASIS MONDAL
I have fixed this by adding which i am using somewhere. So please check your all exports.
我通过添加我在某处使用的来解决这个问题。所以请检查您的所有出口。
module.exports = router;
回答by Tikaram Mardi
Your index.js file is fine you just have to create users.jsand export it.
您的 index.js 文件很好,您只需创建users.js并导出它。
let express = require('express');
let router = express.Router();
//Login Page - GET REQUEST
router.get('/login',(req,res)=> {
res.send('login page');
})
//Register Page - GET REQUEST
router.get('/register',(req,res)=> {
res.send('register page');
});
module.exports = router;
回答by Ankit
If you have checked all the solution than also having this error than check this one
如果你已经检查了所有的解决方案而不是也有这个错误而不是检查这个
Another cause of having this error is calling a method which is not exist or not not exported. In my case i am calling loginmethod but i forgot to define them
出现此错误的另一个原因是调用了不存在或未导出的方法。就我而言,我正在调用登录方法,但我忘记定义它们
I was trying to call this method
我试图调用这个方法
app.post('/api/login', db.login);
but i had forgot to create login method so i got this error. also try to check spelling mistake may be you might have typed wrong spell
但我忘了创建登录方法,所以我收到了这个错误。还尝试检查拼写错误可能是您输入了错误的拼写
回答by Hajar Elkoumikhi
I had the same problem, and then I discovered that I was missing this line in one of my controllers !
我遇到了同样的问题,然后我发现我的一个控制器中缺少这一行!
return api;//it might be return routerfor your code !
return api;//它可能是return router为了你的代码!
I added this line to my code and it worked fine.
我将此行添加到我的代码中,并且运行良好。
回答by Ravinder Reddy Kottabad
in every module **export the router** and **keep one handler for the default
path '/'**
// in index.js
const authRoute = require("./routes/authRoute");
app.use("/auth", authRoute);
// in authRoute.js
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
// code
});
module.exports = router;
回答by Kartik Javali
I found it after lot of struggle! as everything syntactically correct, nothing wrong with code that was written, it was due to the code that was not written yet! This could happen if you have implemented index.js but not yet users.js. However, you have already defined both lines app.use('/', routes); app.use('/users', users); If you are eager to test index.js right away without waiting for users.js to be implemented. That's exactly when it errors out.
经过一番折腾终于找到了!由于一切语法正确,编写的代码没有错,这是由于尚未编写的代码!如果您已实现 index.js 但尚未实现 users.js,则可能会发生这种情况。但是,您已经定义了两行 app.use('/', routes); app.use('/users', 用户); 如果您渴望立即测试 index.js,而无需等待 users.js 的实现。这正是它出错的时候。
回答by Noobmaster
if you are still facing this problem and try every solution then just replace router with routes and it worked fine
如果您仍然面临这个问题并尝试所有解决方案,那么只需用路由替换路由器,它就可以正常工作
回答by kadir
If you use in routes
如果在路由中使用
exports default router
Your solution can be
您的解决方案可以是
module.exports = router
回答by Himavan
This error comes when you forgot to export the module which uses the Router.
当您忘记导出使用路由器的模块时会出现此错误。
Your mentioned code works perfectly with some tweaks.
您提到的代码经过一些调整后可以完美运行。
if your app.js is main/starting point of the app.
如果您的 app.js 是应用程序的主要/起点。
it should have
它应该有
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
instead of
代替
module.exports = app;
(optional)Generally index.js is used for starting point of app. Rename index.js as helloworld.js and change same at require statement
(可选)通常 index.js 用于应用程序的起点。将 index.js 重命名为 helloworld.js 并在 require 语句中更改相同
var routes = require('./routes/index');
to
到
var routes = require('./routes/helloworld');
run this app using the following command
使用以下命令运行此应用程序
node app.js

