官方的文档和社区的帖子都看过了,就是不好使啊。 这是我的代码:
app.configure(function(){
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.cookieSession({ key:"lgyCookie", secret: "mySecret" }));
// 使用flash插件
app.use(flash());
// 动态全局变量
app.use(function(req, res, next){
app.locals({
inspect: function(obj) {
return util.inspect(obj, true);
}
});
next();
}
);
app.use(app.router);
routers(app);
// 静态资源访问
app.use(express.static(__dirname + '/html'));
app.use(express.static(__dirname + '/html/js'));
app.use(express.static(__dirname + '/html/css'));
app.use(express.static(__dirname + '/html/img'));
});
ejs页面:
<%=inspect(headers) %>
控制台报错:
inspect is not defined
8 回复
routers(app);
// 静态资源访问
app.use(express.static(__dirname + '/html'));
app.use(express.static(__dirname + '/html/js'));
app.use(express.static(__dirname + '/html/css'));
app.use(express.static(__dirname + '/html/img'));
放在路由器之前
// 静态资源访问
app.use(express.static(__dirname + '/html'));
app.use(express.static(__dirname + '/html/js'));
app.use(express.static(__dirname + '/html/css'));
app.use(express.static(__dirname + '/html/img'));
routers(app);
app.js
var myUtil = require(‘./myUtil’); app.use(function(req, res, next){ res.locals.myUtil=myUtil; next(); }
myUtil.js
var MyUtil = function () { }; MyUtil.prototype.hello=function (name) { console.log('hello '+name); return 'hello '+name; } module.exports = new MyUtil();
index.ejs
<%=myUtil.hello(‘aaa’)%>
再次感谢你的回复~ 我按照你的建议把代码单独精简出来一个测试项目 试了一下还是不行啊,还是说user undefined这是我的所有代码,您运行一下试试 server.js
var express = require("express");
var ejs = require('ejs');
var fs = require("fs");
var user = require("./User");
var app = express();
var server = require('http').createServer(app);
function start(){
app.configure(function(){
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.cookieSession({ key:"lgyCookie", secret: "mySecret" }));
// 动态全局变量
app.use(function(req, res, next){
res.locals.user = user;
next();
}
);
});
app.get('/test', function(req, res){
res.set({'Content-Type': 'text/html'});
var tmp = fs.readFileSync('home.ejs', 'utf8');
var html = ejs.render(tmp, {message:'lgyhitler'});
res.send(html);
});
server.listen(8888);
console.log("服务器启动...");
}
exports.start = start;
User.js
/**
* 用户实体
*/
function User(){
}
module.exports = new User();
/**
* 根据用户名、密码获得用户
* @user 用户参数
*/
User.prototype.get = function (){
console.log('lgyhitler !!!!!!!!');
return 'lgyhitler!!!!!!!!';
}
index.js
var server = require("./server");
server.start();
视图用的ejs home.ejs
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link type="text/css" rel="stylesheet" href="bootstrap.css" />
<script type="text/javascript" src="jquery-1.7.min.js"></script>
</head>
<body>
<%=user.get() %>
</body>
</html>