Search code examples
javascriptnode.jsexpressmiddleware

Code doesn't serve my static html files in the publlic folder


Exploring express framework. Learning the express.static middleware but it doesn't function the way I expect it to.

Code:

const express = require("express");
const app = express();

app.use((req, res, next) =>{
    express.static('public');
    next();
}); 

app.use((req, res) => {
  console.log("Starting first middleware");
});

app.listen(3000);

The above code doesn't serve my static html files in the publlic folder. The public folder is on the same directory as this JS file, and when I for instance use the URL http://localhost:3000/home.html to try to access the home.html file in the public folder I cannot access it.

When I switch up the order that the express.static is last it does serve my static html file in the public folder.

Code:

app.use((req, res, next) => {
  console.log("Starting first middleware");
  next();
});

app.use(express.static('public'));

Question:

Why doesn't my app in the first code example serve the static files?


Solution

  • express.static is a function that returns another function (middleware), and Express middlewares expect 2 or 3 parameters (req, res[, next]).

    When it is used as a callback, like this:

    app.use(express.static('public'));
    

    you don't need to explicitly provide parameters to it, since app.use will provide them for you.

    However, when you use it yourself, you need to explicitly call the function with its parameters:

    app.use((req, res, next) =>{
        express.static('public')(req, res, next);
        next();
    });
    

    In your first example, you were generating the middleware, but not executing it.