app.all('*')과 app.use('/')의 차이
사이에 유용한 차이점이 있습니까?app.all("*", … )
그리고.app.use("/", … )
Node.js에서 실행되는 Express.js에서?
대부분의 경우 그들은 동등하게 작동합니다.가장 큰 차이점은 미들웨어가 적용되는 순서입니다.
app.all()
응용 프로그램의 라우터에 연결되므로, 항상 사용됩니다.app.router
미들웨어 도달(모든 메서드 경로 처리...GET
,POST
등).
주의:
app.router
Express 4.x에서 더 이상 사용되지 않습니다.
app.use()
응용 프로그램의 기본 미들웨어 스택에 연결되므로 미들웨어에서 지정한 순서대로 사용됩니다. 예를 들어, 먼저 실행하면 가장 먼저 실행됩니다.(라우터 뒤에) 마지막으로 놓으면 일반적으로 전혀 실행되지 않습니다.
일반적으로 모든 경로에 대해 글로벌하게 작업을 수행하려면app.use()
그게 더 나은 선택입니다.또한 express 0.4는 암시적 라우터(즉, 지금 당장 기술적으로 사용할 필요도 없기 때문에 미들웨어에서 라우터의 위치가 지금보다 더 중요함)를 떨어뜨릴 수 있기 때문에 향후 버그가 발생할 가능성이 적습니다.
app.use는 하나의 콜백 기능만 사용하며 미들웨어용입니다.미들웨어는 일반적으로 요청 및 응답을 처리하지 않으며(기술적으로 처리할 수 있음) 입력 데이터를 처리하고 대기열에 있는 다음 처리기로 전달합니다.
app.use([path], function)
app.all은 여러 콜백을 수행하며 라우팅을 의미합니다.여러 콜백을 사용하여 요청을 필터링하고 응답을 보낼 수 있습니다.filters on express.js에 설명되어 있습니다.
app.all(path, [callback...], callback)
app.use는 URL이 지정된 경로로 시작하는지 여부만 확인합니다.
app.use( "/product" , mymiddleware);
// will match /product
// will match /product/cool
// will match /product/foo
app.all이 전체 경로와 일치합니다.
app.all( "/product" , handler);
// will match /product
// won't match /product/cool <-- important
// won't match /product/foo <-- important
app.all( "/product/*" , handler);
// won't match /product <-- Important
// will match /product/
// will match /product/cool
// will match /product/foo
app.사용:
- 전면 컨트롤러에 미들웨어를 주입하여 헤더, 쿠키, 세션 등을 구성합니다.
- app[proxy_proxy] 앞에 써야 합니다. 그렇지 않으면 실행되지 않습니다.
- 여러 호출이 쓰기 순서대로 처리됩니다.
app.all:
- (app[app]_message]와 같이)는 경로의 컨트롤러를 구성하는 데 사용됩니다.
- "all"은 모든 http 메서드에 적용됨을 의미합니다.
- 여러 호출이 쓰기 순서대로 처리됩니다.
다음 expressJs 코드 샘플을 보십시오.
var express = require('express');
var app = express();
app.use(function frontControllerMiddlewareExecuted(req, res, next){
console.log('(1) this frontControllerMiddlewareExecuted is executed');
next();
});
app.all('*', function(req, res, next){
console.log('(2) route middleware for all method and path pattern "*", executed first and can do stuff before going next');
next();
});
app.all('/hello', function(req, res, next){
console.log('(3) route middleware for all method and path pattern "/hello", executed second and can do stuff before going next');
next();
});
app.use(function frontControllerMiddlewareNotExecuted(req, res, next){
console.log('(4) this frontControllerMiddlewareNotExecuted is not executed');
next();
});
app.get('/hello', function(req, res){
console.log('(5) route middleware for method GET and path patter "/hello", executed last and I do my stuff sending response');
res.send('Hello World');
});
app.listen(80);
'/hello' 경로에 액세스할 때의 로그는 다음과 같습니다.
(1) this frontControllerMiddlewareExecuted is executed
(2) route middleware for all method and path pattern "*", executed first and can do stuff before going next
(3) route middleware for all method and path pattern "/hello", executed second and can do stuff before going next
(5) route middleware for method GET and path patter "/hello", executed last and I do my stuff sending response
와 함께app.use()
"장착" 경로가 벗겨지고 미들웨어 기능에 표시되지 않습니다.
app.use('/static', express.static(__dirname + '/public'));
기능 (Mounted MiddlewareFunctions)express.static
가. 그렇지 않습니다.req.url
이 가 포함됩니다(으)로 표시됩니다./static
), 함수가 호출될 때 제거됩니다.
와 함께app.all()
그런 행동은 없습니다.
네.app.all()
DELETE 유형에 관계없이 될 때 됩니다.
에 ㅠㅠㅠapp.use()
사용자가 가지고 있을 수 있는 모든 미들웨어에 사용되며 경로 접두사에 마운트되며 해당 경로의 URI가 요청될 때마다 호출됩니다.
여기 app.all & app.use에 대한 설명서가 있습니다.
위의 두 가지 차이점은 모두 언급되지 않습니다.
번째 째번는첫::
app.all
정규식을 경로 매개 변수로 사용합니다.app.use
정규식을 허용하지 않습니다.
번째두두:
app.all(path, handler)
또는app[method](path, handler)
메뉴얼path
모두에게 동일해야 합니다. path
.이것은,app[method]
경로가 완료되었습니다.
app.use(path, handler)
,한다면use
는 " " 경가완습었니다되료"이어야 처리기의 경로는 다음과 같아야 합니다./
에 약에만.use
의 경로는 전체 경로의 시작이며, 처리기 경로는 전체 경로의 나머지 경로여야 합니다.
app.use("/users", users);
//users.js: the handler will be called when matchs `/user/` path
router.get("/", function (req, res, next) {
res.send("respond with a resource");
});
// others.js: the handler will be called when matches `/users/users` path
router.get("/users", function (req, res, next) {
res.send("respond with a resource");
});
app.all("/users", users);
//others.js: the handler will be called when matches `/`path
router.get("/", function (req, res, next) {
res.send("respond with a resource");
});
//users.js: the handler will be called when matches `/users` path
router.get("/users", function (req, res, next) {
res.send("respond with a resource");
});
두 차이점이 : 가 지 주 차 이 있 습 니 다 점 이 두 요 니 다 있 습 ▁there rences 두 :이 ▁are
패턴 매칭 (팔라니가 준 답변)
2. next(route)
app.use
: 다음문설있습명다니어되링크에서의다▁this있.
NOTE: next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.
링크: http://expressjs.com/en/guide/using-middleware.html
의 작용 next('route')
다음 예에서 확인할 수 있습니다.
app.get('/',
(req,res,next)=>{console.log("1");
next(route); //The code here skips ALL the following middlewares
}
(req,res,next)=>{next();}, //skipped
(req,res,next)=>{next();} //skipped
);
//Not skipped
app.get('/',function(req,res,next){console.log("2");next();});
언급URL : https://stackoverflow.com/questions/14125997/difference-between-app-all-and-app-use
'programing' 카테고리의 다른 글
스프링 MVC 채우기 @RequestParamMap (0) | 2023.08.01 |
---|---|
MariaDB가 소켓을 통해 연결할 수 없음 (0) | 2023.08.01 |
드롭다운 목록(요소 선택)에서 기본 화살표 아이콘을 제거하는 방법은 무엇입니까? (0) | 2023.08.01 |
너비가 있는 CSS 입력: 100%가 상위 경계를 벗어납니다. (0) | 2023.08.01 |
코드백에서 자바스크립트 함수를 호출하는 방법 (0) | 2023.08.01 |