错误:找不到模块'ejs',即使它已在package.json

时间:2016-12-30 17:36:55

标签: node.js express package.json

当我尝试在我的app.js文件中调用路由时,我的应用程序没有加载'EJS'模块,我想知道原因。

我的问题非常similar in scope to this one,但它有一些额外的皱纹,这些皱纹没有在答案中解决,所以我认为我会把它变成一个新问题。

如果我启动一个非常基本的app.js文件,调用ejs它会按预期工作,并且不会出错。

APP.JS:

var express = require('express');
var app = express();

app.set('view engine', 'ejs');

app.get('/', function(req, res){
    res.send("Hello World");
    }).listen(3000, function(){
    console.log("The port is now listening at 3000");
  });

但是,一旦我修改app.js以使用路由来呈现视图,我会在标题中收到错误消息。

以下脚本提供错误:

APP.JS:

var express = require('express');
var app = express();
var root = require('./routes/index');

app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));

app.use(root);

app.listen(3000, function(){
console.log("The port is now listening at 3000");
});

module.exports = app;

我用来建立路由的index.js文件如下所示:

INDEX.JS:

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

/* GET home page. */
router.get('/', function(req, res) {
res.render('index', {
  pageTitle: 'The Formula Generator',
  pageDescription: 'Easily manage and store your supplement formulas',
  pageID: 'home' });
});

module.exports = router;

EJS在我的package.json中正确加载如下:

的package.json:

"dependencies": {
"body-parser": "~1.15.2",
"cookie-parser": "~1.4.3",
"debug": "~2.2.0",
"ejs": "^2.5.5",
"express": "~4.14.0",
"mongodb": "^2.2.16",
"monk": "^3.1.3",
"morgan": "~1.7.0",
"serve-favicon": "~2.3.0"
 },

它也安装在我的node_modules文件夹中。

我的文件结构目前如下所示:

enter image description here

2 个答案:

答案 0 :(得分:1)

<强> app.js

var express = require('express');
var app = express();
var root = require('./routes/index');

app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));

root(app); // pass app to index

app.listen(3000, function(){
console.log("The port is now listening at 3000");
});

module.exports = app;

<强> index.js

var controller = function(app){
    app.get('/', function(req, res) {
    res.render('index', {
      pageTitle: 'The Formula Generator',
      pageDescription: 'Easily manage and store your supplement formulas',
      pageID: 'home' });
    });
};
module.exports = controller;

<强>的package.json

{
  "name": "test",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.2.6",
    "ejs": "*"
  }
}

答案 1 :(得分:1)

在项目的根目录上安装Express。

npm install express --save