From 7fdd970a4345b7ed0796ded46c2261a68b2fce5c Mon Sep 17 00:00:00 2001 From: Andrew Nicolaou Date: Sun, 21 Jul 2019 16:31:14 +0200 Subject: [PATCH] Fixes bug where requestsOfType() would fail if no body - Passes if request has no body - Returns a JSON object with an error message when request doesn't match type, the response body was "[object Object]" --- server/server.js | 11 +++++++++++ server/utils/requestsOfType.js | 9 ++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/server/server.js b/server/server.js index 2ec69ba3..0e6cc859 100644 --- a/server/server.js +++ b/server/server.js @@ -132,6 +132,17 @@ app.get('/', (req, res) => { res.sendFile(renderIndex()); }); +// Handle API errors +app.use('/api', (error, req, res, next) => { + if (error && error.code && !res.headersSent) { + res.status(error.code).json({ error: error.message }); + return; + } + + next(error); +}); + + // Handle missing routes. app.get('*', (req, res) => { res.status(404); diff --git a/server/utils/requestsOfType.js b/server/utils/requestsOfType.js index 20d806d6..5aac7b8c 100644 --- a/server/utils/requestsOfType.js +++ b/server/utils/requestsOfType.js @@ -4,11 +4,14 @@ header does not match `type` */ const requestsOfType = type => (req, res, next) => { - if (req.get('content-type') != null && !req.is(type)) { + const hasContentType = req.get('content-type') !== null; + const isCorrectType = req.is(type) === null || req.is(type) === type; + + if (hasContentType && !isCorrectType) { if (process.env.NODE_ENV === 'development') { - console.log('in requests of type error'); + console.error(`Requests with a body must be of Content-Type "${type}". Sending HTTP 406`); } - return next({ statusCode: 406 }); // 406 UNACCEPTABLE + return next({ code: 406, message: `Requests with a body must be of Content-Type "${type}"` }); // 406 UNACCEPTABLE } return next();