How to do it...

We will write a middleware function that allows access to the root path "/" only when the query parameter allowme is present:

  1. Create a new file named middleware-functions.js
  2. Initialize a new ExpressJS application:
      const express = require('express') 
      const app = express() 
  1. Write a middleware function that will add a property allowed to the request object:
      app.use((request, response, next) => { 
          request.allowed = Reflect.has(request.query, 'allowme') 
          next() 
      }) 
  1. Add a request method to handle requests for path "/":
      app.get('/', (request, response, next) => { 
          if (request.allowed) { 
              response.send('Hello secret world!') 
          } else { 
              response.send('You are not allowed to enter') 
          } 
      }) 
  1. Listen on port 1337 for new connections:
      app.listen( 
          1337, 
          () => console.log('Web Server running on port 1337'), 
      ) 
  1. Save the file
  2. Open a terminal and run:
      node middleware-functions.js
  
  1. To see the results, in your web browser, navigate to:
      http://localhost:1337/
http://localhost:1337/?allowme
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.197.164