Add content-negotiation

This commit is contained in:
Timothy Warren 2016-02-19 16:23:00 -05:00
parent b6dc717a00
commit a57b86257c
5 changed files with 33 additions and 11 deletions

View File

@ -2,6 +2,7 @@
const errors = require('errors');
const express = require('express');
const negotiate = require('express-negotiate');
const path = require('path');
const autoLoad = require('./config/container-autoload');

View File

@ -8,15 +8,21 @@ const container = require('../Container');
const app = container.get('app');
const HTTP_CODE_MAP = require('http').STATUS_CODES;
const errors = require('errors');
const negotiate = require('express-negotiate');
let errorHandlers = new Set([
function handle404(req, res, next) {
// if no route matches, send a 404
function handle400Errors(err, req, res, next) {
if (! req.route) {
let err = new errors.Http404Error();
return next(err);
// if no route matches, send a 404
err = new errors.Http404Error();
} else if (err instanceof negotiate.NotAcceptable) {
// if no content type matches, send a 406
err = new errors.Http406Error();
}
return next(err);
},
// general error handler
@ -36,12 +42,19 @@ let errorHandlers = new Set([
output.error = err;
}
res.render('error', {
title: `${err.status} ${err.message}`,
error: output,
});
// Send html or json depending on client accept header
req.negotiate({
html: () => {
res.render('error', {
title: `${err.status} ${err.message}`,
error: output,
});
},
//res.json(output);
'application/json': () => {
res.json(output);
},
});
},
]);

View File

@ -4,8 +4,12 @@ module.exports = {
'/': {
// Get homepage
get: (req, res) => {
return res.render('index', {
title: 'Blog test page',
req.negotiate({
html: () => {
return res.render('index', {
title: 'Blog test page',
});
},
});
},
},

View File

@ -3,14 +3,17 @@
<h2>{{error.message}}</h2>
{{#if error.error}}
<article>
<center>
<table>
<caption>Error Details</caption>
{{#each error as |value key|}}
<tr>
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
{{/each}}
</table>
</center>
</article>
{{/if}}
</main>

View File

@ -11,6 +11,7 @@
"eslint": "^1.10.3",
"express": "4.*",
"express-handlebars": "^3.0.0",
"express-negotiate": "0.0.5",
"express-session": "^1.13.0",
"getargs": "0.0.8",
"glob": "^6.0.4",