bootstrappedUser - Jade or EJS to HTML

耗尽温柔 提交于 2019-12-10 11:40:06

问题


I've been doing some guide on Mean stack and I came to a point where I'm currently stuck. Following this guide, I have created a simple authentication where I'm able to log in using Passport JS. Whatsoever, each time when page refreshes, the authentication gets restarted (client doesn't recognise it anymore).

Since this is suppose to happen in the guide and we are about to fix it, guide said the following. 1. Create a Jade file and insert this:

    if !!bootstrappedUser
  script.
    window.bootstrappedUserObject = !{JSON.stringify(bootstrappedUser)}

I've tried this in my html file but it doesn't work:

  <script type='text/javascript'>

          if (bootstrappedUser != "undefined" ){
          window.bootstrappedUserObject = JSON.stringify(bootstrappedUser);
           }

    </script>

Getting the error: Uncaught ReferenceError: bootstrappedUser is not defined even though I have created the variable in my backend js file and assigned req.user to it.

I'm suppose to have this file included in my main layout (index.html). The problem is that I'm not using Jade as template engine but plain HTML and I don't know how to transform this code up there to work as simple HTML in my index.html.

It seams that this statement up here only initialise when user hits the login button. Does anyone have any idea or solution how to write the above code in plain HTML.

I browsed StackOverflow and found almost similar problems but not similar enough. Thanks in advance, Aleksandar


回答1:


bootstrappedUser is a variable passed by server-side code to Jade compiler which injects it into the HTML while compiling. If you plan on writing the HTML yourself you can not inject variables from server-side code, obviously because HTML is just a static markup. You'll probably have to get that variable at the client-side from the server yourself via ajax or something.

Via Angular controller let's say ?

You can first define a route on server that serves the variable you want

app.get('/bootstrappedUser', function(req, res){
    if(req.user)
        res.json(req.user);
    else
        res.status(401).end();
});

Then on client-side angular you can perform an http request and get that variable

$http.get('/bootstrappedUser')
    .success(function(data, status, headers, config) {
        $scope.bootstrappedUser = data;
    });


来源:https://stackoverflow.com/questions/26477351/bootstrappeduser-jade-or-ejs-to-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!