上QQ阅读APP看书,第一时间看更新
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:
- Create a new file named middleware-functions.js
- Initialize a new ExpressJS application:
const express = require('express') const app = express()
- 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() })
- 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') } })
- Listen on port 1337 for new connections:
app.listen( 1337, () => console.log('Web Server running on port 1337'), )
- Save the file
- Open a terminal and run:
node middleware-functions.js
- To see the results, in your web browser, navigate to:
http://localhost:1337/
http://localhost:1337/?allowme