Skip to content

Instantly share code, notes, and snippets.

@simonespa
Created August 10, 2020 16:51
Show Gist options
  • Select an option

  • Save simonespa/3c79959b2010970993521ca97fb5e6dc to your computer and use it in GitHub Desktop.

Select an option

Save simonespa/3c79959b2010970993521ca97fb5e6dc to your computer and use it in GitHub Desktop.
Express JS
const express = require('express')
const basicAuth = require('express-basic-auth')
const app = express()
app.use('/secret', basicAuth({
users: { 'sounds': 'supersecret' },
unauthorizedResponse: (req) => {
return req.auth ? ('Credentials rejected') : 'No credentials provided'
},
challenge: true,
realm: 'Imb4T3st4pp'
}))
app.get('/secret', (req, res) => res.send('The secret is revealed'))
app.listen(8080, () => console.log('Example app listening on port 8080!'))
const express = require('express');
const app = express();
function throwError(request, response, next) {
throw new Error('Error thrown');
}
function nextWithError(request, response, next) {
next(new Error('Next with Error'));
}
function asynchError(request, response, next) {
new Promise((resolve, reject) => {
setTimeout(function () {
reject('Asynch Error');
}, 2000);
}).catch(error => {
next(new Error(error));
});
}
function uncatchedError(request, response, next) {
undefined.catch(error => {
next(new Error(error));
});
}
function notFound(request, response) {
response.status(404).json({
page: 'Not Found'
});
}
function errorHandler (error, request, response, next) {
if (response.headersSent) {
return next(err);
}
response.status(500).json({
page: 'Error handler',
error: error.message
});
}
app.get('/throwError', throwError);
app.get('/nextWithError', nextWithError);
app.get('/asynchError', asynchError);
app.get('/uncatchedError', uncatchedError);
app.get('*', notFound);
app.use(errorHandler);
const port = 8080;
app.listen(port, error => {
if (error) {
return console.log(error.message);
}
console.log(`Process started listening on port ${port}`);
});
const express = require('express');
const app = express();
const port = 8080;
let counter = 0;
app.set('etag', 'strong');
app.set('query parser', 'extended');
app.disable('x-powered-by');
app.get('/', (req, res) => {
counter += 1;
let body = `Counter: ${counter}`;
res.status(200);
res.send(body);
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment