Skip to content

Instantly share code, notes, and snippets.

@w3cj
Created June 15, 2017 17:19
Show Gist options
  • Save w3cj/8a06a1a04b0d5e56560dc5761d162d41 to your computer and use it in GitHub Desktop.
Save w3cj/8a06a1a04b0d5e56560dc5761d162d41 to your computer and use it in GitHub Desktop.
const express = require('express');
const app = express();
// app.use === generic, will be called for every request
app.use((req, res, next) => {
console.log(req.originalUrl, 'Time:', new Date());
req.time = new Date();
next();
});
// app.get === specific, will be called for every GET request that matches the path
// Why don't we call next here???
app.get('/', (req, res, next) => {
res.json({
message: 'Hello World!'
});
});
app.post('/things/:id', (req, res, next) => {
if(req.params.id == 42) {
res.json({
message: 'The answer'
});
} else {
next(new Error('You are wrong.'));
}
});
// HAS TO BE THE LAST MIDDLEWARE!!!
app.use((req, res, next) => {
res.status(404);
next(new Error('Not found.'));
});
app.use((error, req, res, next) => {
res.json({
message: error.message,
stack: process.env.NODE_ENV == 'production' ? {} : error.stack
});
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment