Add content-negotiation
This commit is contained in:
parent
b6dc717a00
commit
a57b86257c
@ -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');
|
||||
|
||||
|
@ -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);
|
||||
},
|
||||
});
|
||||
},
|
||||
]);
|
||||
|
||||
|
@ -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',
|
||||
});
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
|
@ -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>
|
@ -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",
|
||||
|
Reference in New Issue
Block a user