Basic Node and Express - Implement a Root-Level Request Logger Middleware

Basic Node and Express - Implement a Root-Level Request Logger Middleware
0

#1

I can’t understand plz somebody help me to explain this.

app.get(’/json’, function(req, res, next){
console.log();
next();
})


#2

The challenge asks you to implement a root-level logger middleware.
Let’s break it down into pieces:

  • root-level logger middleware. :
    Basically it means that you should implement a “function” triggered by incoming requests regardless of the path the request is directed to.

  • root-level logger middleware. :
    Nothing more than what it means literally - is just a “function” whose objective is to ‘log’ something ( output to console / write into file / … some data)

  • root-level logger middleware. :
    A “function” executed ‘during the travel’ of your request to the response.

Now, the challenge instructions explicit how you should build this function:

For every request, it should log in the console a string taking the following format: method path - ip

Break it down again:

  • For every request, it should log in the console a string taking the following format: method path - ip:
    It means that you don’t need to be more specific ( app.post, app.delete, app.get, …), you can just use app.use as suggested in the instructions.

  • For every request, it should log in the console a string taking the following format: method path - ip:
    Well, basically here it’s asking you to use the console.log method

  • For every request, it should log in the console a string taking the following format: method path - ip:
    And here it’s telling you what to log ( the arguments of console.log method).

Now the only problem is to retrieve the information you need to log: this is what the following statement was made for:

You can get the request method (http verb) [method path - ip ], the relative route path[method path - ip], and the caller’s ip [method path - ip] from the request object, using req.method, req.path and req.ip

About your code:

app.get(’/json’, function(req, res, next){
console.log();
next();
})
  • You don’t need app.get ( which would be triggered only when the request uses a GET method - you want to execute the function for every incoming request ( GET, POST, DELETE, …)

  • You shouldn’t use/json : it will execute the function only when the requests are directed to the /json path and you want to process all the requests.

  • Inside the console.log method you should use the arguments indicated above.

Good luck! :slight_smile:


#3

app.use( (req, res, next)=>{
console.log("req.method+ ’ ‘+req.path+’-’+req.ip ");
next();
})

Root level logger middleware should be active


#4

Thanks so much I solved it


#5

Thanks for the breakdown and step by step explanation. Really helped