Last active
June 20, 2019 01:49
-
-
Save harrisonmalone/28e1b1597906a1a22001333962a5bc00 to your computer and use it in GitHub Desktop.
middleware basics ☀️
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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