Research/Server
Koa_파라미터 조건에 따른 미들웨어 실행하기
RIEM
2023. 10. 31. 22:55
728x90
Koa에서 next()를 생략하면 다음 미들웨어는 실행하지 않는다. 이 원리를 이용해서 파라미터의 값에 따라 화면을 다르게 렌더링할 수 있다.
// index.js
const Koa = require('koa');
const app = new Koa();
app.use((ctx, next) => {
console.log(ctx.url);
console.log(1);
if (ctx.query.authorized !== '1') {
ctx.status = 401; // Unauthorized
return;
}
next();
});
app.use((ctx, next) => {
console.log(2);
next();
});
app.use((ctx) => {
ctx.body = 'hello world';
});
app.listen(4000, () => {
console.log('Listening to port 400');
});
localhost:4000/ 접속 시
localhost:4000/?authorized=1 접속 시
728x90