我试图在Node.js和Express框架中创建控制器。
我已创建app.js
,routes/index.js
和controller/index.js
。
以下是每个文件代码:
var express = require("express"),
path = require("path"),
indexRoutes = require("./routes/index");
var app = express();
app.use("view engine", "ejs");
app.use("views", path.join(__dirname, "views"));
app.use("/", indexRoutes);
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("listening to port " + port);
});
routes/index.js
:
var express = require("express");
var controller = require("../controller/index");
var router = express.Router();
router.get("/", controller.index);
router.get("/list", controller.list);
module.exports = router;
controller/index.js
:
var indexController = {
index: function(req, res) {
res.send("index action");
},
list: function(req, res) {
res.send("list action");
}
}
module.exports = indexController;
当我运行服务器时。我的终端出现了这个错误:
Error: Router.use() requires callback functions but got a [object String]
at Function.proto.use (/media/misc/www/expself/node_modules/express/lib/router/index.js:327:11)
at Function.app.use (/media/misc/www/expself/node_modules/express/lib/application.js:195:16)
at Object.<anonymous> (/media/misc/www/expself/app.js:7:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
有任何帮助吗?我是node.js的初学者
答案 0 :(得分:0)
这些:
app.use("view engine", "ejs");
app.use("views", path.join(__dirname, "views"));
应该是:
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use()
仅适用于中间件。