node.js - How Does Middleware Actually Work? -
i'm curious nodejs , express. how middleware work? how go creating own middleware?
does rely on type of dependency injection? understand add middleware in order want executed, , http request/response passed middleware, , onto next, , next, until 1 of them returns/renders request/response.
are request , response objects passed through each middleware reference?
sorry if sounds confusing. i'm trying learn how create own middleware better understanding of in general.
edit: post written express 3. minor details have changed since then, it's conceptually same.
a note before start: express built atop connect, handles middleware. when write express
in these examples, i'd able write connect
.
at bottom level, have node's http server module. looks kind of this:
var http = require("http"); http.createserver(function(request, response) { response.end("hello world!\n"); }).listen(1337, "localhost");
basically, make single function handles all http requests. try running above code , visiting localhost:1337/hello or localhost:1337/wow-anime. technically, need!
but let's want many functions run every time. maybe want add command-line logger, , maybe want make every request plain text.
var http = require("http"); http.createserver(function(request, response) { // logger console.log("in comes " + request.method + " " + request.url); // plain text response.writehead(200, { "content-type": "text/plain" }); // send response response.end("hello world!\n"); }).listen(1337, "localhost");
in express/connect, might write instead:
var express = require("express"); var app = express(); app.use(express.logger()); app.use(function(request, response, next) { response.writehead(200, { "content-type": "text/plain" }); next(); }); app.use(function(request, response) { response.end("hello world!\n"); }); app.listen(1337);
i think of middlewares list of functions. when http request comes in, start @ top , go through each middleware top bottom, , stop when response.end
called (or response.send
in express).
i wrote a blog post explains express , middleware in more detail, if you're interested.
Comments
Post a Comment