Static Files and Middleware

  • cookieParse is a middleware
  • middleware has a next() function
  • middleware is sitting between the request and response

An common middleware example

  • We need to handle static files being downloaded
  • You don't want to manually deal with CSS and images etc...
  • Create a public folder and put all your static files in it
  • app.use() tells node you're using a middleware

Making your own middleware

//just match a route, and takes a function with request and response(middleware will sit in between them and handle thing)
//We also need a third parameter called next
//whenever this route hits, it will call this function below
app.use('/', function(req, res, next) {

});

Big Word

Middleware: Code that sits between two layers of software.

In the case of Express, sitting between the request and the response.

Static: Not dynamic.

In other words, not processed by code in any way. For example HTML, CSS and image files are 'static' files.

The Code

var express = require('express');
var app = express();

var port = process.env.PORT || 3000;

//this part is using middleware too
//we are using a express built-in middleware called static to handle static files
//when *localhost:3000/assets/stanley.jpg* is requested, it will get redirected to *localhost:3000/public/stanley.jpg*
//__dirname + '/public' tells node where to find the files physically
//when node see /assets , it will pass it to the middleware, middleware will translate and get that file for me
app.use('/assets', express.static(__dirname + '/public'));

//this is the middleware part I think, not fully understand yet
app.use('/', function (req, res, next) {
    console.log('Request Url:' + req.url);
    next();
});

app.get('/', function(req, res) {
    res.send('<html><head><link href=assets/style.css type=text/css rel=stylesheet /></head><body><h1>Hello world!</h1></body></html>');
});

app.get('/person/:id', function(req, res) {
    res.send('<html><head></head><body><h1>Person: ' + req.params.id + '</h1></body></html>');
});

app.get('/api', function(req, res) {
    res.json({ firstname: 'John', lastname: 'Doe' });
});

app.listen(port);

results matching ""

    No results matching ""