简体   繁体   中英

Express error - TypeError: express.Router is not a function

I'm going through this tutorial by thenewboston using Express, EJS, and Node. My code is almost exactly set up like his, except at the end using app.listen instead of module.exports = send.

I get the following error when I try to run my node program:

var router = express.Router();
                 ^
TypeError: express.Router is not a function

Here is my 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');

// uncommet 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(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward error to handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.listen(3000, function(){
  console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});

and my index.js file is:

var express = require('express'); 
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

I've done a similar tutorial before, and didn't have this problem arise. Any idea what could be causing this?

Working with EcmaScript modules (files extension .mjs) and node version v12.16.1 and with "express": "~4.16.1" I faced the same error.

In my case, since it was used import * as express from 'express'; instead of require, I had to change import statement to import express from 'express'; and the issue was solved.

Try this - obtained from sample code from express/lib/application.js.

var http = require('http') ,https = require('https) ,express = require('express')

var app = express()

Worked for me. Most likely, only one or the other of http / https is required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM