Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added client-side data exposing example
- Loading branch information
Showing
2 changed files
with
82 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
|
||
var express = require('../..') | ||
, app = express(); | ||
|
||
app.set('view engine', 'jade'); | ||
app.set('views', __dirname + '/views'); | ||
|
||
function User(name) { | ||
this.private = 'heyyyy'; | ||
this.secret = 'something'; | ||
this.name = name; | ||
this.id = 123; | ||
} | ||
|
||
// You'll probably want to do | ||
// something like this so you | ||
// dont expose "secret" data. | ||
|
||
User.prototype.toJSON = function(){ | ||
return { | ||
id: this.id, | ||
name: this.name | ||
} | ||
}; | ||
|
||
app.use(express.logger('dev')); | ||
|
||
// earlier on expose an object | ||
// that we can tack properties on. | ||
// all res.locals props are exposed | ||
// to the templates, so "expose" will | ||
// be present. | ||
|
||
app.use(function(req, res, next){ | ||
res.locals.expose = {}; | ||
// you could alias this as req or res.expose | ||
// to make it shorter and less annoying | ||
next(); | ||
}); | ||
|
||
// pretend we loaded a user | ||
|
||
app.use(function(req, res, next){ | ||
req.user = new User('Tobi'); | ||
next(); | ||
}); | ||
|
||
// if you wanted to _always_ expose | ||
// the user you might do something like this: | ||
/* | ||
app.locals.use(function(req, res){ | ||
if (req.user) res.locals.expose.user = req.user; | ||
}) | ||
*/ | ||
|
||
app.get('/', function(req, res){ | ||
res.redirect('/user'); | ||
}); | ||
|
||
app.get('/user', function(req, res){ | ||
// we only want to expose the user | ||
// to the client for this route: | ||
res.locals.expose.user = req.user; | ||
res.render('page'); | ||
}); | ||
|
||
app.listen(3000); | ||
console.log('app listening on port 3000'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
html | ||
head | ||
title Express | ||
script | ||
// call this whatever you like, | ||
// or dump them into individual | ||
// props like "var user =" | ||
var data = !{JSON.stringify(expose)} | ||
body | ||
h1 Expose client data | ||
p The following was exposed to the client: | ||
pre | ||
script | ||
document.write(JSON.stringify(data, null, 2)) |