Last active
October 7, 2020 14:07
-
-
Save hilleer/81600a2686895eb5f434b2faec1e9033 to your computer and use it in GitHub Desktop.
Express middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const createHttpError = require('http-errors'); | |
const app = express(); | |
app.get('/foo', | |
middlewareOne, | |
middlewareTwo, | |
fooHandler | |
); | |
// should come after all other route handlers | |
app.use(errorHandler); | |
app.listen(3000, () => console.log('listening')); | |
function middlewareOne(req, res, next) { | |
console.log('hit middleware one'); | |
const secretHeader = req.get('x-secret-header'); | |
if (secretHeader !== 'valid-value') { | |
res.status(403).end(); | |
// important | |
return; | |
} | |
next(); | |
} | |
function middlewareTwo(req, res, next) { | |
console.log('hit middleware two'); | |
const { id | |
} = req.body; | |
const isValidId = (id) => typeof id === 'string'; | |
if (!isValidId(id)) { | |
res.status(400).json({ | |
message: 'bad id' | |
}); | |
// important | |
return; | |
} | |
next(); | |
} | |
function fooHandler(req, res, next) { | |
try { | |
// do some logic that might throw | |
} catch (error) { | |
next(error); // forward error to error handler | |
} | |
} | |
function errorHandler(err, req, res, next) { | |
const httpError = createHttpError(err); | |
const { status | |
} = httpError; | |
res.status(status).json(httpError); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment