Skip to content

Instantly share code, notes, and snippets.

@philkeys
Last active August 29, 2015 14:26
Show Gist options
  • Save philkeys/f3c0f0f0d790a29cbfc0 to your computer and use it in GitHub Desktop.
Save philkeys/f3c0f0f0d790a29cbfc0 to your computer and use it in GitHub Desktop.
WebDev with Node and Express => Rendering content with Express
// basic usage
app.get('/about', function (req, res) {
res.render('about');
});
// response codes other than 200
app.get('/error', function (req, res) {
res.status(500);
res.render('error');
});
// response codes other than 200 (on one line)
app.get('/error', function (req, res) {
res.status(500).render('error');
});
// Passing context to a view including querystring, cookie, and session values
app.get('/greeting', function (req, res) {
res.render('about', {
message: 'welcome',
style: req.query.style,
userid: req.cookie.userid,
username: req.session.username
});
});
// rendering a view without a layout
// the following layout doesn't have a layout file, so views/no-layout.handlebars
// must include all necessary HTML
app.get('/no-layout', function (req, res) {
res.render('no-layout', { layout: null });
});
// rendering a view with a custom layout
// the layout files views/layouts/custom.handlebars will be used
app.get('/custom-layout', function (req, res) {
res.render('custom-layout', { layout, 'custom' });
});
// rendering plaintext output
app.get('/test', function (req, res) {
res.type('text/plain');
res.send('This is a test');
});
// Adding an error handler
// This should appear AFTER all of your routes, note that even
// if you don't need the 'next' function, it must be included
// for Express to recognize this as an error handler
app.use(function (err, req, res, next) {
console.log(err.stack);
res.status(500).render('error');
});
// Adding a 404 handler
// this should appear AFTER all of your routes
app.use(function (req, res) {
res.status(404).render('not-found');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment