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