Skip to content

Commit

Permalink
Added client-side data exposing example
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed Apr 19, 2012
1 parent de6f300 commit 9780838
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
68 changes: 68 additions & 0 deletions examples/expose-data-to-client/index.js
@@ -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');
14 changes: 14 additions & 0 deletions examples/expose-data-to-client/views/page.jade
@@ -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))

0 comments on commit 9780838

Please sign in to comment.