forked from codefellows/seattle-javascript-401d30
-
Notifications
You must be signed in to change notification settings - Fork 0
07 Express
Jagdeep Singh edited this page May 22, 2019
·
1 revision
Any number of functions that are invoked by the the Express.js routing layer before your final request handler is made.
All middleware functions have an optional next parameter which is the function to run next (callback).
Request —> Route -> [CORS —> CSRF —> Auth] —> Main task —> Response
// Psuedo-Code
let express = require('express');
let app = express();
let port = process.env.PORT || 8080;
app.get('/', (req, res) => {
// middleware
cors.initialize();
auth.verify();
// final request handler
function(req, res) {
res.render('index');
}
});
app.post('/upload', auth.isAuthenticated(), controller.upload);Router is like a mini express application, it doesn't bring in views or settings, but provides us with routing APIs like .use, .get, .param, and .route.
// server.js
// get an instance of router
var router = express.Router();
// home page route (http://localhost:8080)
router.get('/', function(req, res) {
res.send('im the home page!');
});
// about page route (http://localhost:8080/about)
router.get('/about', function(req, res) {
res.send('im the about page!');
});
// apply the routes to our application
app.use('/', router);- can create multiple
express.Router()- can have a Router for our basic routes, authenticated routes, and even API routes.
- allows us to make our applications more modular and flexible than ever before by creating multiple instances of the Router and apply them accordingly.