Why does middleware return GET not USE?

Tell us what’s happening:
Describe your issue in detail here.
So I passed the “Implement a root level request logger middleware” with the code below. But when I read my logs the output is get. Why is req.method GET when I did not use that command at all in my middleware?

Your code so far

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.83 Safari/537.36

Challenge: Implement a Root-Level Request Logger Middleware

Link to the challenge:

If you read the docs it explains it. Start by looking at the text above the first two examples.

We can expand on it if needed.

1 Like

So I see that “Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.” So my understanding from this is that use is not an HTTP method. Maybe I should be focusing more on what HTTP methods are?

Then here “The function is executed for any type of HTTP request on the /user/:id path.”

app.use('/user/:id', (req, res, next) => {
  console.log('Request Type:', req.method)
  next()
})

It seems to say that the use method in express gets called for any type of HTTP request. So is it that by going to a website I’m sending a get request to my server? How would I send a post or put request to get the req.method to output something else? Can a user do that or are those only backend terms?

The handler function in an app.method (get/post/whatever) is technically part of the middleware system, they are often called a controller. You can chain middleware.

function someMiddleware(req, res, next) {
  ...do something
  next();
}

app.get('/', someMiddleware, (req, res) => {
  ...handle get
})

The someMiddleware will only run on that specific method and path (before the controller). The controller doesn’t have to be inline it can be defined like the middleware.

/controllers
  handleSomething.js
  
/middleware
  someMiddleware.js
app.get('/', someMiddleware, handleSomething);

If you want the middleware to run on all methods and paths (root level) you use it before the routes (use can also take a path).

app.use(someMiddleware);

app.get('/', handleSomething);
app.post('/', handleSomething);

Yes.

Such requests might come from an HTML form, or client JS code making an API call (like a fetch with an HTTP method to some path).