Expressjs에서 미들웨어 및 app.use는 실제로 무엇을 의미합니까?
내가 본 거의 모든 Express 앱에는 app.use
미들웨어에 대한 설명이 있지만 실제로 미들웨어가 무엇이며 app.use
명령문이 무엇을하고 있는지에 대한 명확하고 간결한 설명을 찾지 못했습니다 . 명시 적 문서 자체조차도 약간 모호합니다. 이 개념들을 설명해 주시겠습니까?
새 프로젝트에서 미들웨어 개념을 분리하는 과정이 반쯤 진행되었습니다.
미들웨어를 사용하면 처리해야 할 작업 스택을 정의 할 수 있습니다. Express 서버 자체는 미들웨어의 스택입니다.
// express
var app = express();
// middleware
var stack = middleware();
그런 다음 호출하여 미들웨어 스택에 레이어를 추가 할 수 있습니다 .use
// express
app.use(express.static(..));
// middleware
stack.use(function(data, next) {
next();
});
미들웨어 스택의 계층은 함수이며, n 개의 매개 변수 (표현식 req
&에 대한 2 res
)와 next
함수를 갖습니다.
미들웨어는 계층이 계산을 수행하고 매개 변수를 보강 한 다음을 호출 할 것으로 예상합니다 next
.
스택은 처리하지 않으면 아무것도하지 않습니다. Express는 들어오는 HTTP 요청이 서버에서 잡힐 때마다 스택을 처리합니다. 미들웨어를 사용하면 스택을 수동으로 처리합니다.
// express, you need to do nothing
// middleware
stack.handle(someData);
보다 완전한 예 :
var middleware = require("../src/middleware.js");
var stack = middleware(function(data, next) {
data.foo = data.data*2;
next();
}, function(data, next) {
setTimeout(function() {
data.async = true;
next();
}, 100)
}, function(data) {
console.log(data);
});
stack.handle({
"data": 42
})
명시 적으로 용어는 들어오는 모든 HTTP 요청에 대해 명시 적으로 처리하려는 작업 스택을 정의합니다.
연결이 아닌 Express (익스프레스) 측면에서 글로벌 미들웨어가 있고 특정 미들웨어를 라우팅합니다. 즉, 들어오는 모든 HTTP 요청에 미들웨어 스택을 첨부하거나 특정 경로와 상호 작용하는 HTTP 요청에만 미들웨어 스택을 첨부 할 수 있습니다.
익스프레스 및 미들웨어의 고급 예 :
// middleware
var stack = middleware(function(req, res, next) {
users.getAll(function(err, users) {
if (err) next(err);
req.users = users;
next();
});
}, function(req, res, next) {
posts.getAll(function(err, posts) {
if (err) next(err);
req.posts = posts;
next();
})
}, function(req, res, next) {
req.posts.forEach(function(post) {
post.user = req.users[post.userId];
});
res.render("blog/posts", {
"posts": req.posts
});
});
var app = express.createServer();
app.get("/posts", function(req, res) {
stack.handle(req, res);
});
// express
var app = express.createServer();
app.get("/posts", [
function(req, res, next) {
users.getAll(function(err, users) {
if (err) next(err);
req.users = users;
next();
});
}, function(req, res, next) {
posts.getAll(function(err, posts) {
if (err) next(err);
req.posts = posts;
next();
})
}, function(req, res, next) {
req.posts.forEach(function(post) {
post.user = req.users[post.userId];
});
res.render("blog/posts", {
"posts": req.posts
});
}
], function(req, res) {
stack.handle(req, res);
});
일을 단순화 한 후 웹 서버는 요청을 받아 응답을 출력하는 함수로 볼 수 있습니다. 따라서 웹 서버를 함수로 볼 경우 웹 서버를 여러 조각으로 구성하고 더 작은 기능으로 분리하여 구성이 원래 기능이 될 수 있습니다.
미들웨어는 다른 사람과 구성 할 수있는 더 작은 기능이며 재사용 할 수 있다는 것이 명백한 이점입니다.
나는 이전 답변에서 언급되지 않은 것을 추가하기 위해 늦은 답변을 추가합니다.
이제 미들웨어가 클라이언트 요청 과 서버 응답 사이에서 기능한다는 것을 분명히해야합니다 . 가장 일반적인 미들웨어 기능은 오류 관리, 데이터베이스 상호 작용, 정적 파일 또는 기타 리소스에서 정보 얻기입니다. 미들웨어 스택에서 이동하려면 다음 콜백을 호출해야합니다. 미들웨어 기능의 끝에서 플로우의 다음 단계로 이동하는 것을 볼 수 있습니다.
app.use
접근 방식을 사용하고 다음 과 같은 흐름을 가질 수 있습니다 .
var express = require('express'),
app = express.createServer(),
port = 1337;
function middleHandler(req, res, next) {
console.log("execute middle ware");
next();
}
app.use(function (req, res, next) {
console.log("first middle ware");
next();
});
app.use(function (req, res, next) {
console.log("second middle ware");
next();
});
app.get('/', middleHandler, function (req, res) {
console.log("end middleware function");
res.send("page render finished");
});
app.listen(port);
console.log('start server');
그러나 다른 접근 방식을 사용하고 각 미들웨어를 함수 인수로 전달할 수도 있습니다. 다음은 midoware가 클라이언트로 다시 전송 되기 전에 midleware가 Twitter, Github 및 블로그 플로우를 얻는 MooTools Nodejs 웹 사이트 의 예입니다response
. 에서 함수가 인수로 전달되는 방식에 유의하십시오 app.get('/', githubEvents, twitter, getLatestBlog, function(req, res){
. 사용 app.get
은 GET 요청에 대해서만 app.use
호출되며 모든 요청에 대해 호출됩니다.
// github, twitter & blog feeds
var githubEvents = require('./middleware/githubEvents')({
org: 'mootools'
});
var twitter = require('./middleware/twitter')();
var blogData = require('./blog/data');
function getLatestBlog(req, res, next){
blogData.get(function(err, blog) {
if (err) next(err);
res.locals.lastBlogPost = blog.posts[0];
next();
});
}
// home
app.get('/', githubEvents, twitter, getLatestBlog, function(req, res){
res.render('index', {
title: 'MooTools',
site: 'mootools',
lastBlogPost: res.locals.lastBlogPost,
tweetFeed: res.locals.twitter
});
});
expressjs 가이드 는 귀하의 질문에 대한 깔끔한 답변을 제공합니다. 가이드의 짧은 스 니펫을 게시하고 있으며 가이드는 매우 좋습니다.
Express 앱에서 사용할 미들웨어 작성
개요
미들웨어 함수는 요청 오브젝트 ( req ), 응답 오브젝트 ( res ) 및 애플리케이션의 요청-응답주기에서 다음 함수에액세스 할 수있는함수입니다. 다음 기능은 Express 라우터의 기능으로, 호출 될 때 현재 미들웨어에 이어 미들웨어를 실행합니다.
미들웨어 기능은 다음 작업을 수행 할 수 있습니다.
- 모든 코드를 실행하십시오.
- 요청 및 응답 오브젝트를 변경하십시오.
- 요청-응답주기를 종료하십시오.
- 스택에서 다음 미들웨어를 호출하십시오.
현재 미들웨어 함수가 요청-응답주기를 종료하지 않으면 next () 를 호출 하여 제어를 다음 미들웨어 함수로 전달 해야합니다 . 그렇지 않으면 요청이 중단됩니다.
예
Here is an example of a simple “Hello World” Express application. The remainder of this article will define and add two middleware functions to the application: one called myLogger that prints a simple log message and another called requestTime1 that displays the timestamp of the HTTP request.
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000)
Middleware function myLogger
Here is a simple example of a middleware function called “myLogger”. This function just prints “LOGGED” when a request to the app passes through it. The middleware function is assigned to a variable named myLogger.
var myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
Notice the call above to next(). Calling this function invokes the next middleware function in the app. The next() function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The next() function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.
To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).
var express = require('express')
var app = express()
var myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
app.use(myLogger)
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000)
Every time the app receives a request, it prints the message “LOGGED” to the terminal.
The order of middleware loading is important: middleware functions that are loaded first are also executed first.
If myLogger is loaded after the route to the root path, the request never reaches it and the app doesn’t print “LOGGED”, because the route handler of the root path terminates the request-response cycle.
The middleware function myLogger simply prints a message, then passes on the request to the next middleware function in the stack by calling the next() function.
- This post will only contain myLogger middleware, for further post you could go to the original expressjs guide here.
=====Very very simple explanation=====
Middlewares are often used in the context of Express.js framework and are a fundamental concept for node.js . In a nutshell, Its basically a function that has access to the request and response objects of your application. The way I'd like to think about it, is a series of 'checks/pre-screens' that the request goes through before the it is handled by the application. For e.g, Middlewares would be a good fit to determine if the request is authenticated before it proceeds to the application and return the login page if the request is not authenticated or for logging each request. A lot of third-party middlewares are available that enables a variety of functionality.
Simple Middleware example:
var app = express();
app.use(function(req,res,next)){
console.log("Request URL - "req.url);
next();
}
The above code would be executed for each request that comes in and would log the request url, the next() method essentially allows the program to continue. If the next() function is not invoked, the program would not proceed further and would halt at the execution of the middleware.
A couple of Middleware Gotchas:
- The order of middlewares in your application matters, as the request would go through each one in a sequential order.
- Forgetting to call the next() method in your middleware function can halt the processing of your request.
- Any change the req and res objects in the middleware function, would make the change available to other parts of the application that uses req and res
Middlewares are functions executed in the middle after the input/source then produces an output which could be the final output or could be used by the next middleware until the cycle is complete.
It is like a product that goes through an assembly line where it gets modified as it moves along until it gets completed, evaluated or gets rejected.
A middleware expects some value to work on (i.e. parameter values) and based on some logic the middleware will call or not call the next middleware or send a response back to the client.
If you can't still grasp the middleware concept, it is in a way similar to the Decorator or Chain of command patterns.
Middleware is a subset of chained functions called by the Express js routing layer before the user-defined handler is invoked. Middleware functions have full access to the request and response objects and can modify either of them.
The middleware chain is always called in the exact order in which it has been defined, so it is vital for you to know exactly what a specific piece of middleware is doing.
Once a middleware function finishes, it calls the next function in the chain by invoking its next argument as function.
After the complete chain gets executed,the user request handler is called.
Keep things simple, man!
Note: the answer is related to the ExpressJS builtin middlware cases, however there are different definitions and use cases of middlewares.
From my point of view, middleware acts as utility or helper functions but its activation and use is fully optional by using the app.use('path', /* define or use builtin middleware */)
which don't wants from us to write some code for doing very common tasks which are needed for each HTTP request of our client like processing cookies, CSRF tokens and ..., which are very common in most applications so middleware can help us do these all for each HTTP request of our client in some stack, sequence or order of operations then provide the result of the process as a single unit of client request.
Example:
Accepting clients requests and providing back responses to them according to their requests is the nature of web server technology.
Imagine if we are providing a response with just "Hello, world!" text for a GET HTTP request to our webserver's root URI is very simple scenario and don't needs anything else, but instead if we are checking the currently logged-in user and then responding with "Hello, Username!" needs something more than usual in this case we need a middleware to process all the client request metadata and provide us the identification info grabbed from the client request then according to that info we can uniquely identify our current user and it is possible to response to him/her with some related data.
Hope it to help someone!
In very basic term if i want to explain it like this i learn this from traversymedia youtube channel express crash course.
ok so middle ware is a function who execute after you make a call to your route like this.
var logger = function(req, res, next){
console.log('logging...');
next();
}
app.use(logger);
This logger function execute every time you refresh your page that means you can write anything in it that you required to do after your page get rendered any operation api call, reset things basically anything. and put this middleware before your route function order of middleware is really important or it dons't work
'Programing' 카테고리의 다른 글
-XAllowAmbiguousTypes는 언제 적절한가요? (0) | 2020.04.29 |
---|---|
폭탄 적하 알고리즘 (0) | 2020.04.29 |
서브 프로세스 stdout을 한 줄씩 읽으십시오 (0) | 2020.04.29 |
파이썬에서“with”블록으로 돌아 오면 파일이 여전히 닫히나요? (0) | 2020.04.29 |
사용자 정의 반복자와 const_iterator를 올바르게 구현하는 방법은 무엇입니까? (0) | 2020.04.29 |