Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Last active June 20, 2019 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harrisonmalone/28e1b1597906a1a22001333962a5bc00 to your computer and use it in GitHub Desktop.
Save harrisonmalone/28e1b1597906a1a22001333962a5bc00 to your computer and use it in GitHub Desktop.
middleware basics ☀️
const express = require('express');
const app = new express();
// middleware
const firstMiddleware = (req, res, next) => {
// a return in the middleware
// go to the next thing in the middleware chain
console.log('in first middleware')
next()
}
const secondMiddleware = (req, res, next) => {
console.log('in second middleware')
req.addingToTheRequest = "adding to the request"
next()
}
const thirdMiddleware = (req, res, next) => {
console.log(req.addingToTheRequest)
next()
}
const onlyInRickAndMortyGet = (req, res, next) => {
console.log('in the middleware for rick and morty get')
next()
}
// global middleware
// app.use(express.json())
// app.use(express.urlencoded({extended: true}))
app.use(firstMiddleware)
app.use(secondMiddleware)
app.post('/rick-and-morty', thirdMiddleware, (req, res) => {
console.log(req)
// console.log(req.addingToTheRequest)
res.send('hello')
})
// specific middleware, local middleware
app.get('/rick-and-morty-get', onlyInRickAndMortyGet, (req, res) => {
res.send('in rick and morty get')
})
app.listen(3000, () => console.log('listening on port 3000'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment