javascript - Express error - TypeError: Router.use() requires middleware function but got a Object -
i getting error when run npm start run express app.
typeerror: router.use() requires middleware function got object
my app.js code
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 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 , forwarding error handler app.use(function(req, res, next) { var err = new error('not found'); err.status = 404; next(err); }); /// error handlers // development error handler // 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 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.js code
var express = require('express'); var router = express.router(); /* home page. */ router.get('/', function(req, res) { res.render('index', { title: 'express' }); }); /* hello world page. */ router.get('/helloworld', function(req, res) { res.render('helloworld', { title: 'hello, world!' }) }); module.exports = router;
i quirte new using node , express. cant see have gone wrong. can see problem is?
i found answer in comments kop4lyf:
check users.js. should exporting router index.js, if can try that.
however, question top search result when ran issue, promoting answer.
the error caused because 1 of route modules not being exported - meaning express not have access when tries identify of routes.
you can fix adding module.exports = router;
end of each of route files.
example:
var express = require('express'); var router = express.router(); router.get('/', function(req, res, next) { //do whatever... }); module.exports = router;
more information module.exports
can found on this question or offcial node.js documentation.
Comments
Post a Comment