NodeJS 本地变量在ejs脚本中不可访问

dtcbnfnu  于 2023-05-22  发布在  Node.js
关注(0)|答案(1)|浏览(258)

我希望能够在用户登录后设置全局变量,并在应用程序的任何脚本中引用它们。这样做的原因是为了避免大量页面传递相同的值。
我的index.js是这样开始的:

var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path');

var app = express();

app.set('view engine', 'ejs');
app.use("/static", express.static('./views/pages/'));

app.locals.uaccId = "";         // These are my globals
app.locals.uaccName = "";
app.locals.uaccOrgId = "";
app.locals.uaccOrgName = "";
app.locals.uaccEmail= "";

app.use(session({
   secret: 'secret',
   resave: true,
   saveUninitialized: true
}));

app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());

成功登录后(使用数据库),我在request.session中设置了一些值,这些值用于设置app.locals的值(我以为我可以在EJS页面中引用request,但我发现我不能):

app.post('/auth', function(request, response) {
   console.log ( '/auth' );
   let lgn = require( "./mods/auth.js");
   lgn.login(request, response);    // Sets values in request.session
   app.locals.uaccId =       request.session.uaccId,
   app.locals.uaccName =   request.session.uaccName,
   app.locals.uaccOrgId =    request.session.uaccOrgId,
   app.locals.uaccOrgName =  request.session.uaccOrgName;
   app.locals.uaccEmail =  request.session.uaccEmail;
});

现在,当我呈现任何页面时,我希望在页面标题中显示一些用户详细信息,因此在我的ejs文件中,我有:

<header>
  <%- include('../partials/header'); %>
</header>

然后header.ejs有:

<div class='toplink'> <%= uaccName.replace(/ .*/, '') %>  </div>
      <div class='toplink'> @ <%= uaccOrgName %>      </div>

但是当我运行这个时,我得到:

TypeError: /u01/WorkSpace/node/views/pages/index.ejs:10
    8| 
    9| <header>
 >> 10|   <%- include('../partials/header'); %>
    11| </header>
    12| 
    13| <div class='centerBox'>

/u01/WorkSpace/node/views/partials/header.ejs:6

 >> 6|       <div class='toplink'> <%= uaccName.replace(/ .*/, '') %>  </div>
    7|       <div class='toplink'> @ <%= uaccOrgName %>      </div>

Cannot read property 'replace' of undefined
yr9zkbsy

yr9zkbsy1#

我没有点击我下面的代码不只是在启动时执行-它将得到执行,每次请求一个路由。
我在上面的app.use(bodyParser.json());行之后添加了以下内容,然后它开始工作。

app.use(function(request, response, next){
   response.locals.uaccId       = "";
   response.locals.uaccName     = "";
   response.locals.uaccOrgId    = "";
   response.locals.uaccOrgName  = "";
   response.locals.uaccEmail    = "";
   if (request.session.uaccId)      response.locals.uaccId       =  request.session.uaccId;      
   if (request.session.uaccName)    response.locals.uaccName     =  request.session.uaccName;    
   if (request.session.uaccOrgId)   response.locals.uaccOrgId    =  request.session.uaccOrgId;   
   if (request.session.uaccOrgName) response.locals.uaccOrgName  =  request.session.uaccOrgName; 
   if (request.session.uaccEmail)   response.locals.uaccEmail    =  request.session.uaccEmail;   
   next();      
})

相关问题