Passing a variable from node.js to html

后端 未结 9 1258
孤独总比滥情好
孤独总比滥情好 2020-11-27 18:12

I am trying to pass a variable from node.js to my HTML file.

app.get(\'/main\', function(req, res) {
  var name = \'hello\';
  res.render(__dirname + \"/view         


        
相关标签:
9条回答
  • 2020-11-27 18:23

    use res.json, ajax, and promises, with a nice twist of localStorage to use it anywhere, added with tokens for that rare arcade love. PS, you could use cookies, but cookies can bite on https.

    webpage.js

    function (idToken) {
        $.ajax({
            url: '/main',
            headers: {
                Authorization: 'Bearer ' + idToken
            },
            processData: false,
        }).done(function (data) {
            localStorage.setItem('name', data.name);
            //or whatever you want done.
        }).fail(function (jqXHR, textStatus) {
            var msg = 'Unable to fetch protected resource';
            msg += '<br>' + jqXHR.status + ' ' + jqXHR.responseText;
            if (jqXHR.status === 401) {
                msg += '<br>Your token may be expired'
            }
            displayError(msg);
        });
    

    server.js, using express()

    app.get('/main',
    passport.authenticate('oauth2-jwt-bearer', { session: false }),
    function (req, res) {
        getUserInfo(req) //get your information to use it.
            .then(function (userinfo) {  //return your promise
                res.json({ "name": userinfo.Name});
                //you can declare/return more vars in this res.json.
                //res.cookie('name', name); //https trouble
            })
        .error(function (e) {console.log("Error handler " + e)})
        .catch(function (e) {console.log("Catch handler " + e)});
    });
    
    0 讨论(0)
  • 2020-11-27 18:29

    I have achieved this by a http API node request which returns required object from node object for HTML page at client ,

    for eg: API: localhost:3000/username

    returns logged in user from cache by node App object .

    node route file,

    app.get('/username', function(req, res) {
        res.json({ udata: req.session.user });
        });
    
    0 讨论(0)
  • 2020-11-27 18:31

    What you can utilize is some sort of templating engine like pug (formerly jade). To enable it you should do the following:

    1. npm install --save pug - to add it to the project and package.json file
    2. app.set('view engine', 'pug'); - register it as a view engine in express
    3. create a ./views folder and add a simple .pug file like so:
    html
      head
        title= title
      body
        h1= message
    

    note that the spacing is very important!

    1. create a route that returns the processed html:
    app.get('/', function (req, res) {
      res.render('index', { title: 'Hey', message: 'Hello there!'});
    });
    

    This will render an index.html page with the variables passed in node.js changed to the values you have provided. This has been taken directly from the expressjs templating engine page: http://expressjs.com/en/guide/using-template-engines.html

    For more info on pug you can also check: https://github.com/pugjs/pug

    0 讨论(0)
  • 2020-11-27 18:34

    With Node and HTML alone you won't be able to achieve what you intend to; it's not like using PHP, where you could do something like <title> <?php echo $custom_title; ?>, without any other stuff installed.

    To do what you want using Node, you can either use something that's called a 'templating' engine (like Jade, check this out) or use some HTTP requests in Javascript to get your data from the server and use it to replace parts of the HTML with it.

    Both require some extra work; it's not as plug'n'play as PHP when it comes to doing stuff like you want.

    0 讨论(0)
  • 2020-11-27 18:34

    Other than those on the top, you can use JavaScript to fetch the details from the server. html file

    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
          <div id="test">
          </div>
        <script type="text/javascript">
            let url="http://localhost:8001/test";
            fetch(url).then(response => response.json())
            .then( (result) => {
                console.log('success:', result)
                let div=document.getElementById('test');
                div.innerHTML=`title: ${result.title}<br/>message: ${result.message}`;
            })
            .catch(error => console.log('error:', error));
        </script>
      </body>
    </html>
    

    server.js

    app.get('/test',(req,res)=>{
        //res.sendFile(__dirname +"/views/test.html",);
        res.json({title:"api",message:"root"});
    })
    
    app.get('/render',(req,res)=>{
        res.sendFile(__dirname +"/views/test.html");
    })
    

    The best answer i found on the stack-overflow on the said subject, it's not my answer. Found it somewhere for nearly same question...source source of answer

    0 讨论(0)
  • 2020-11-27 18:43

    I figured it out I was able to pass a variable like this

    <script>var name = "<%= name %>";</script>
    console.log(name);
    
    0 讨论(0)
提交回复
热议问题