Home > OS >  what happens in app.use(express.static) and app.use(require("cors")()) and what middleware
what happens in app.use(express.static) and app.use(require("cors")()) and what middleware

Time:12-06

I started with express a few days ago. I dont really understand what happens in:

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

app.use(express.static(path.join(), "public")) 
    
app.use(require("cors")())

app.listen(3000, () => console.log("running"))

the first example worked for me but i dont really understand it. and basiclly i dont understand what happens in app.use() and what middlewares are..

someone can help me pls? i read many blogs and I didnt got it :(

CodePudding user response:

The Background

There are several parts to explaining this. First, off app.use() expects a middleware function to be passed to it. That would be a function with a signature like this:

app.use(function(req, res, next) {
    console.log(req.path);      // log incoming request path
    next();                     // continue routing to other handlers
});

It accepts other combinations of parameters, including an initial path and you can pass multiple middleware functions too and it will chain them together, but the basics of your question is about a single middleware function as shown above. That middleware function gets three arguments req - the incoming request object, res - the outgoing response objet and next - a function to call if you want to continue routing or report an error.

The job of one of these middleware function is to use the input in the req object to do some kind of processing of that input (depending upon what the purpose of the middleware function is) and then do one of three things:

  1. Send a response using something like res.send() in which case the request has been handled and a response has been sent and no further routing will be done.

  2. Continue routing to further request handlers in the chain by calling next().

  3. Abort routing and go to the Express error handler by calling next(err).


The express.static() Middleware

So, that's what is expected of a function passed to app.use(). Now, let's look at the two examples you ask about. Let's start with express.static():

app.use(express.static(path.join(), "public")) 

First, this isn't proper use of express.static(). I'm not sure exactly what you intended, but I will assume you meant something like this:

app.use(express.static(path.join(__dirname, "public"))); 

In this case, express.static() takes some configuration information which is the resulting path from calling path.join(__dirname, "public") and uses that to create a custom middleware function. So, calling express.static(path.join(__dirname, "public")) returns a function that expects to be called with the three middleware arguments we previously discussed. It is logically identical to this:

const publicPath = path.join(__dirname, "public");
const myStaticMiddleware = express.static(publicPath);
app.use(myStaticMiddleware);

which is logically equivalent to this:

const publicPath = path.join(__dirname, "public");
const myStaticMiddleware = express.static(publicPath);
app.use(function(req, res, next) {
    myStaticMiddleware(req, res, next);
});

Where the code has been broken down into separate steps just so you can see each step separately.

And, in case you didn't already know, the point of the express.static() middleware is to serve static files from a designated directory if an incoming request matches a filename in that designated directory exactly and has an appropriate file type.


The cors Middleware

For your second example:

app.use(require("cors")())

Let's again break that down to the individual steps:

const cors = require("cors");   // load cors module
const corsMiddleware = cors();  // create cors middleware function
app.use(corsMiddleware);        // register middleware with Express server

Which can be expanded to:

const cors = require("cors");
const corsMiddleware = cors();
app.use(function(req, res, next) {
    corsMiddleware(req, res, next);
});

Just to show you that corsMiddleware is called with these three arguments.

The purpose of this particular middleware is to help configure a response to this request so that cross origin requests will be accepted.

  • Related