Passing a variable from node.js to html

后端 未结 9 1376
孤独总比滥情好
孤独总比滥情好 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 += '
    ' + jqXHR.status + ' ' + jqXHR.responseText; if (jqXHR.status === 401) { msg += '
    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)});
    });
    

提交回复
热议问题