如何设置要在所有ejs文件中使用的局部变量

时间:2019-01-27 14:06:56

标签: node.js express ejs node-modules

我正在/login路由器中设置本地变量,如以下代码所示 res.locals.username = data[0].username;我同时使用console.logdata[0].username的{​​{1}}输出了,它显示了用户名。

res.locals.username

但是当我尝试在我的ejs中显示“用户名”局部变量时,它表明未定义用户名。这是ejs文件

exports.login = function (req,res,next) {
var username = req.param("username");
var password = req.param("password");

con.query("select * from user where username = '"+username+"' and password = '"+password+"'",function (err,data) {
    if(err) {
        throw err;
    }else {
        if (data.length > 0) {
            if (data[0].username === username && data[0].password === password) {
                console.log(data);
                req.session.userID = data[0].id;
                req.session.username = data[0].username;
                res.locals.username = data[0].username;
                res.redirect("/home");
                next();
            }
    }
});
}; 

exports.home = function (req,res,next){
    if(req.session.userID && req.session.username) {
        res.render('home');
    }
}

它也返回错误

<html>
     <head>
          <title></title>
     </head>
         <body>
      <%= username %>
     </body>
    </html>

这是我的app.js文件

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:482:11)
    at ServerResponse.header (C:\xamppp\htdocs\belajarnode\latihancrudajax2\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\xamppp\htdocs\belajarnode\latihancrudajax2\node_modules\express\lib\response.js:170:12)
    at done (C:\xamppp\htdocs\belajarnode\latihancrudajax2\node_modules\express\lib\response.js:1004:10)
    at tryHandleCache (C:\xamppp\htdocs\belajarnode\latihancrudajax2\node_modules\ejs\lib\ejs.js:257:5)
    at View.exports.renderFile [as engine] (C:\xamppp\htdocs\belajarnode\latihancrudajax2\node_modules\ejs\lib\ejs.js:480:10)
    at View.render (C:\xamppp\htdocs\belajarnode\latihancrudajax2\node_modules\express\lib\view.js:135:8)
    at tryRender (C:\xamppp\htdocs\belajarnode\latihancrudajax2\node_modules\express\lib\application.js:640:10)
    at Function.render (C:\xamppp\htdocs\belajarnode\latihancrudajax2\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (C:\xamppp\htdocs\belajarnode\latihancrudajax2\node_modules\express\lib\response.js:1008:7)
GET /home 500 10.334 ms - 1627

这是我的路线文件

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');

var app = express();

var user = function (req,res,next){
  req.date = Date.now();
  next();
};
app.use(user);
app.use(session({
  secret: 'ysn852jd48'
}));

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');



// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

1 个答案:

答案 0 :(得分:0)

您必须将locals放在路由器方法中的路由文件中。例如,在您的routes/index文件中,您可以通过以下方式使用本地语言:

router.use(function (req, res, next) {
    res.locals.username = req.username;
    next();
});
/* GET home page. */
router.post('/login',controllerdata2.login);
router.get('/', controllerdata2.list_data);
router.get('/register',controllerdata2.register);
router.get('/home',controllerdata2.home);
...

因此,在您导出的每种方法中,您都可以访问username
在当前代码中,当您在controllerdata2中调用home方法时,您无权访问username,因为尚未使用res.locals进行定义。按照我向您展示的方式,res.locals控制器中的每个方法都将定义为controllerdata2