웹개발
express.js ) app.get vs app.use vs app.all
jjnll
2023. 2. 8. 16:01
결론:
.get → GET HTTP 요청값 하나만 받음. 미들웨어 안거치고 지정된 엔드포인트(특정 하나의 값)로 바로 감.
.use, .all → 모든 HTTP 요청값들(get, post, put, delete)을 받으며 중간에 미들웨어를 탐.
파라메터값까지 포함하여 해당경로값을 가진 모든 함수를 탐.
해당값을 가지는 함수가 많을 경우 cannot set headers 에러 뜸
.use vs .all 차이점
use →
regex 불가
싱글 콜백. url의 시작점만 적용.(cf. '/app'이면 /app/changeData, /app/:id ... 모두 적용된다.)
all →
regex 가능
멀티플 콜백. url 전체 값을 적용.(cf. '/app'이면 /app/*, /app/changeData, /app/:id ...는 적용되지 않음. '/app/*'이면 /app은 적용되지 않음.)
app.use처럼 전체에 적용시키려면 app.all('*', fn)쓰면 된다.
과정:
app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject
app.all( "/book" , handler);
// will match /book
// won't match /book/author
// won't match /book/subject
app.all( "/book/*" , handler);
// won't match /book
// will match /book/author
// will match /book/subject
Summary for app.all('*', fn) vs. app.use(fn):
- No difference in order of execution.
- app.use() fires regardless of methods, app.all() only fires for parser supported methods (probably not relevant since the node.js http parser supports all expected methods).
Summary for app.all('/test', fn) vs. app.use('/test', fn):
- No difference in order of execution
- app.use() fires regardless of methods, app.all() only fires for parser supported methods (probably not relevant since the node.js http parser supports all expected methods).
- app.use() fires for all paths that start with /test include /test/1/ or /test/otherpath/more/1. app.all() only fires if its an exact match to the requested url.x
728x90