Express apps have a use() function. This function adds a new middleware to the app.

For example, suppose you want to print the HTTP method (get, post, etc.) and the URL of every request. Here’s how you can add a new middleware that prints the HTTP method and URL of every request:

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

app.use((req, res, next) => {
  // For example, a GET request to `/test` will print "GET /test"
  console.log(`${req.method} ${req.url}`);

  next();
});

app.get('/test', (req, res, next) => {
  res.send('ok');
});

// Test the above app using Axios
const server = await app.listen(3000);

const axios = require('axios');
// Prints "get /test"
const res = await axios.get('http://localhost:3000/test');

The Middleware Stack

In Express, everything is middleware. Internally, an Express app has a middleware stack, and calling use() adds a new layer to the stack. Functions that define route handlers, like get() and post() also add layers to the stack. Express executes the middleware stack in order, so the order in which you call use() matters.

For example, one of the most common middleware functions is the cors middleware, which attaches CORS headers to your Express HTTP responses. Make sure you call app.use(cors()) before defining any route handlers or anything else that sends an HTTP response, otherwise you won’t get CORS headers!

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

// This response will **NOT** have CORS headers, because order matters.
// Express will run the CORS middleware _after_ this route handler.
app.get('/nocors', (req, res) => {
  res.send('ok');
});

app.use(require('cors')());

// This response will have CORS headers, because this route handler
// is after the CORS middleware in the middleware list.
app.get('/cors', (req, res) => {
  res.send('ok');
});

#express #node #javascript #web-development #developer

The `app.use()` Function in Express
18.65 GEEK