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]"
This commit is contained in:
parent
d4914983a4
commit
cd21e9ae72
2 changed files with 17 additions and 3 deletions
|
@ -138,6 +138,17 @@ app.get('/', (req, res) => {
|
||||||
res.sendFile(renderIndex());
|
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.
|
// Handle missing routes.
|
||||||
app.get('*', (req, res) => {
|
app.get('*', (req, res) => {
|
||||||
res.status(404);
|
res.status(404);
|
||||||
|
|
|
@ -4,11 +4,14 @@
|
||||||
header does not match `type`
|
header does not match `type`
|
||||||
*/
|
*/
|
||||||
const requestsOfType = type => (req, res, next) => {
|
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') {
|
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();
|
return next();
|
||||||
|
|
Loading…
Reference in a new issue