라우터의 파라미터를 설정 할 때는 /about/:name 형식으로 :를 사용하여 라우트 경로를 설정합니다.
파라미터가 있을 수도 있고 없을 수도 있다면 /about/:name? 형식으로 ?를 뒤에 추가합니다.
설정한 파라미터는 ctx.params 객체에서 조회가 가능합니다
Url쿼리의 경우, 예를들어 /post/?id=10 같은 형식으로 요청했다면 ctx.query에서 조회할 수 있습니다.
문자열 형태의 쿼리를 조회해야 할 때는 ctx.querystring을 사용합니다.
index.js
const Koa = require('koa');
const Router = require("koa-router");
const app = new Koa();
const router = new Router();
//라우터 설정
router.get("/", ctx => {
ctx.body = "홈"
});
router.get('/about/:name?', ctx => {
const {name} = ctx.params
ctx.body = name ? `${name}의 소개` : "소개";
})
router.get("/posts", ctx =>{
const {id} = ctx.query;
ctx.body = id ? `포스트 #${id}` : "포스트 아이디가 없습니다"
})
//app 인스턴스에 라우터 적용
app.use(router.routes()).use(router.allowedMethods());
app.listen(4000, () =>{
console.log("Listening to port 4000");
})
http://localhost:4000/about/naver
http://localhost:4000/posts?id=10
http://localhost:4000/posts
위 링크들에 들어가면 경로에 따라 다른결과물이 나타나게 됩니다!
아무튼 실행댐 사진찍었는데 날아가서 패스
특정 조건을 만족하는 항목을 보여줄지 또는 어떤 기준으로 정렬할지를 정해야 할 때 쿼리를 사용합니다.