-2

The node.js code I produced works fine, I just wanted to understand why app.use(passwordProtected) doesn't run when accessing the '/' endpoint, only runs for '/advanced-view'.

I would have thought because they are multiple asynchronous operations, the passwordProtected function would run for '/' as well:

app.get('/', function(req, res) { .... }

app.use(passwordProtected)

app.get('/advanced-view', function(req, res) { ... }

Thanks in advance for any help.

Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • Have you considered moving the `app.use(…)` invocation to *above* your `/` route definition? – esqew Jul 04 '22 at 11:35
  • Does this answer your question? [NodeJS/Express app.use sequence and usage](https://stackoverflow.com/questions/27317119/nodejs-express-app-use-sequence-and-usage) – esqew Jul 04 '22 at 11:37
  • Middlewares are run in the top-to-bottom order. Move `app.use(passwordProtected)` at the top and you will get the expected result. – Yousaf Jul 04 '22 at 11:40
  • Thanks @Yousaf, I understand it now. The code works as it should. – Ralphie Jul 04 '22 at 11:48

1 Answers1

0
  1. The app.use() function is used to mount the specified middleware function (are the functions that have access to the request object and response object, or we can call it a response-request cycle) at the path which is being specified. The middleware function is executed when the base of the requested path matches the path.

  2. app.get(): This function tells the server what to do when get requests at a given route.