Response functions to provide text, JSON, and empty responses in Express JS
// Import the needed middleware functions:
const { Ok200, NotFound404, Unauthorized401 } = require('responsify-express');
// Pass strings to the functions to send them as strings:
app.get('/', Ok200('<p>Welcome to the very short homepage</p>'));
// Or pass objects (or arrays) to send as JSON:
app.get('/settings', Ok200(mySettingsObject));
// Or send empty responses by executing the functions with no arguments:
app.get('/unimplemented', NotFound404())
// Or provide an Error object:
app.get('/bad-route', NotAuthorized401(Error('Bad Route!'))) //sends JSON: {"error": "Bad Route!"}
// ...or don't even execute them, just pass them in:
app.get('/admin', Unauthorized401);Import responsify and then app.use it before any routes that need the response functions:
const { responsify } = require('responsify-express');
app.use(responsify);
app.get('/settings', mySettingsRoute);Then, in the route, you'll find the functions available on the res object...
function mySettingsRoute(req, res, next) {
database.lookup({ name: req.body.name })
.then((foundUser)=>{
if (foundUser) res.Ok200(foundUser.settingsObject);
else res.NotFound404('User not found');
})
.catch((err)=>{
res.InternalError500(err);
});
}When responsify is used as Express middleware, it adds the entire set of functions to the response object:
const { responsify } = require('responsify-express');
app.use(responsify);Functions added to the response object take the form MessageDescription###, where:
MessageDescriptionis a description of the HTTP status code; all functions are named in PascalCase###is the HTTP status code; the status code will be helpful for quick reference when you're writing the front end, and will help you to memorize the codes quicklypayloadis an optional payload to be sent
- If
payloadis an object or array (evaluated usingtypeof payload === 'object), then it is sent as JSON usingres.json(payload). - If
payloadis falsey, then an empty response is sent usingres.end(). - Otherwise, the value is sent as a string using
res.send(String(payload)). (Non-string forms are thus coerced into strings.)
Note: When used from the res response object, the functions must be executed to work. (See examples below)
function myRoute(req, res, next) {
if (!req.body.name) res.BadRequest400('No name specified');
res.Ok200('Request received'); // Send a plain string
res.Ok200({newName: 'Gertrude'}); // Send an object as JSON
res.Ok200([user1, user2, user3]); // Send an array as JSON
res.NotFound404('Content not found'); // Add error message
res.NotFound404({err: caughtError}); // Add error object
res.NotFound404(""); // These both send empty responses with
res.NotFound404(); // a 404 status code.
res.NotFound404; // Doesn't work! (works only when used as middleware)
}Each function must be imported:
const { Ok200, BadRequest400, Unauthorized401, NotFound404 } = require('responsify-express');Functions can then be passed to Express's app.METHOD, router.METHOD, app.use, etc. functions, to give quick in-line responses:
- Function names are as described above for the functions added to the
responseobject—PascalCase with appended numeric status codes - Optional
payloadis sent as a string, object, or empty response, as described above. - When the response functions are used like this, directly as Express middleware, you can provide an empty response either be executing with no arguments, or by just passing the function without executing it:
// These are equivalent:
app.get('/', NotFound404());
app.get('/', NotFound404); //works here, if no response content is requiredconst app = express();
// Settings Routes:
app.get('/settings', getSettings);
app.post('/settings', Unauthorized401('Not logged in'));
app.get('/adminsettings', Unauthorized401('Not available!'));
// Home page
app.get('/', homepage);
// Last resort:
app.use(NotFound404('Page not found'));
app.listen(3000,()=>console.log("Listening..."));Ok200Created201Accepted202NonAuthoritative203NoContent204ResetContent205PartialContent206MultiStatus207AlreadyReported208IMUsed226
BadRequest400Unauthorized401PaymentRequired402Forbidden403NotFound404NotAllowed405NotAcceptable406ProxyAuthRequired407RequestTimeout408Conflict409Gone410LengthRequired411PreconditionFailed412PayloadTooLarge413URITooLong414UnsupportedMedia415RangeNotSatisfiable416ExpectationFailed417ImATeapot418MisdirectedRequest421UnprocessableEntity422Locked423FailedDependency424TooEarly425UpgradeRequired426PreconditionRequired428TooManyRequests429HeaderFieldsTooLarge431UnavailableForLegal451
InternalError500NotImplemented501BadGateway502ServiceUnavailable503GatewayTimeout504VersionNotSupported505VariantAlsoNegotiates506InsufficientStorage507LoopDetected508NotExtended510NetworkAuthRequired511