Open NickBerilov opened 6 years ago
@NickBerilov Please rewrite the article
@Czech-nut The tool found a lot of matches between the article and the official Express documentation and other articles about Express, most of them being terminology (e.g. application-level middleware
, end the request-response cycle
) and common code. Considering that the main goal of the article is to concisely convey everything about middleware from said documentation I will be unable to rewrite it without either avoiding the essential terms and code examples (making the article pointless) or completely changing the topic
You might've heard about ExpressJS: probably the most popular Node.js framework. You might've also heard the word middleware a whole lot. But what is middleware?
Your standard Express-application usually consists of a bunch of routes (also calles endpoints), as well as a number of handlers for each of these routes, which are executed consecutively. These handlers are called middleware. Now let's go into some detail.
Middleware functions (except for error-handling middleware, we'll cover them later) have access to the request object (
req
), response object (res
), as well as thenext
middleware function. Middleware functions can do several things:req
andres
objectsres.end()
orres.send()
)next
middleware function (if the current middleware function doesn't end the request-response cycle, it should callnext()
, or the request will be left hanging)Here's an example: let's have a look at a simple "Hello world" app.
The '/' route has a single middleware function that ends the request-response cycle by responding with "Hello world!". And here's a simple logger function:
Now, there are multiple ways to add this function as a middleware function. You can:
app.use
):There are several types of middleware:
app.use()
orapp.METHOD()
makes it application-level middleware. It's important to note here that the order in which you add application-level middleware to your app matters: as with all types of middleware, application-level middleware will be executed (or checked for, in case of routes) in order it was defined.express.Router()
next()
function (except the string 'route') will skip any remaining non-error-handling middleware an pass control to the first error-handling middleware. Unlike other middleware function, error-handling middleware accept four arguments:err
,req
,res
,next
:express.static
, which is used to serve static content:See the official documentation for more details
cookie-parser
,body-parser
).To sum up, middleware functions make Express apps customizable and easy to build by allowing to add stuff like error-handlers, validation, loggers and application logic to both single and multiple routes, as well as increase functionality by adding libraries as midleware functions.