express middleware Flashcards
How do you mount a middleware with an express application ?
Middleware is the function passed to .use().
Which objects does the express application pass to the middleware to manage the request/response lifecycle of a server?
The request object & the response object
What is middleware and what can middleware do?
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
Middleware functions can perform the following tasks:
Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.
What does the express.json() middleware do and when would you need it?
This is a built-in middleware function in Express. It parses incoming requests with JSON payloads. Returns middleware that only parses JSON and only looks at requests where the Content-Type header matches the type option. A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body), or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.