Skip to content

Instantly share code, notes, and snippets.

@itsravenous
Last active May 8, 2017 20:57
Show Gist options
  • Save itsravenous/48cc8aa85cac1853427018fe8495b4b3 to your computer and use it in GitHub Desktop.
Save itsravenous/48cc8aa85cac1853427018fe8495b4b3 to your computer and use it in GitHub Desktop.
Node server which always 500s (with CORS support!)
{
"name": "thefamous500",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"express": "^4.15.2"
},
"scripts": {
"start": "node server.js"
}
}
const server = require('express')();
// Log requests
server.use((req, res, next) => {
console.log(req.method, req.url);
next();
});
// CORS
server.use((req, res, next) => {
// Echo back request configuration in "allowed" headers
if(req.headers.origin) res.setHeader('access-control-allow-origin', req.headers.origin);
if(req.headers['access-control-request-headers']) res.setHeader('access-control-allow-headers', req.headers['access-control-request-headers']);
if(req.headers['access-control-request-method']) res.setHeader('access-control-allow-methods', req.headers['access-control-request-method']);
// Tell browser not to cache preflight responses
res.setHeader('access-control-max-age', 0);
// Allow credentials
res.setHeader('Access-Control-Allow-Credentials', 'true');
if(req.method === 'OPTIONS') res.end();
else next();
});
// Always serve 500s
const STATUS = process.env.STATUS || 500;
server.use((req, res) => {
res.sendStatus(STATUS);
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server listening on ::${PORT}; will respond to requests with status ${STATUS}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment