简体   繁体   中英

bootstrappedUser - Jade or EJS to HTML

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

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;
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM