[英]Express error - TypeError: express.Router is not a function
I'm going through this tutorial by thenewboston using Express, EJS, and Node.我正在阅读 newboston 使用 Express、EJS 和 Node.js 编写的本教程。 My code is almost exactly set up like his, except at the end using app.listen instead of module.exports = send.我的代码几乎和他的一样设置,除了最后使用 app.listen 而不是 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:这是我的 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:我的 index.js 文件是:
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.使用 EcmaScript 模块(文件扩展名 .mjs)和节点版本v12.16.1
以及"express": "~4.16.1"
我遇到了同样的错误。
In my case, since it was used import * as express from 'express';
就我而言,因为它被用于import * as express from 'express';
instead of require, I had to change import statement to import express from 'express';
而不是要求,我不得不将导入语句更改为import express from 'express';
and the issue was solved.问题就解决了。
Try this - obtained from sample code from express/lib/application.js.试试这个 - 从 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.很可能,只需要 http / https 中的一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.