Middleware is called every time a route is accessed.
const express = require('express')
const app = express()
const projectRouter = require('./routes/projects')
const { users } = require('./data')
// MIDDLEWARE
app.use(express.json())
app.use(setUser)
app.use('/projects', projectRouter)
app.get('/', (req, res) => {
const whiz = req.foo || 'not set'
res.send(`Home page: ${whiz}`)
})
app.get('dashboard', (req, res) => {
res.send('Dashboard page')
})
app.get('/admin', (req, res) => {
res.send('Admin page')
})
function foo(req, res, next) {
req.foo = 'ding'
next()
}
function setUser(req, res, next) {
const userId = req.body.userId
if (userId) {
req.user = users.find(user => user.id === userId)
}
next()
}
// START SERVER
// todo: put in server.js
const PORT = process.env.PORT || 3000
app.listen(PORT, () => {
console.log(`=== server started on port: ${PORT} ===`)
})