var express = require('express')
app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
var server = app.listen(process.env.PORT || 3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
Then start the server:
$ node app.js
DEMO
Form handling requires CSRF protection
Middleware
Think of middleware as plugins
Middleware examples
add to app.js
function iDoNothingAtAll(req, res, next) {
console.log("Tom was here.")
next()
}
function iLikeErrorMessages(req, res, next) {
next("Stop the app from working.")
}
app.use(iDoNothingAtAll)
app.use('/error', iLikeErrorMessages)
Error handling is done via middleware
with an arity of 4
function myErrorHandler(err, req, res, next) {
res.send('This error was caught. ')
}
app.use(myErrorHandler)
All error handling middleware should be defined after all other middleware and route calls.
What can you do with Middleware?
Logging
Serve Static Files
Error Handling
CSRF
Built-in middleware
app.use(express.static('public'));
Node will now server up static assets in the public directory.