- 여러개의 Router를 생성하게 될텐데, 이렇게 되면 유지보수가 이후에는 어려워질수 있으니 router 모듈화를 진행
src/api/index.js
에 api에 관련된 호출을 나열
src/index.js
const Koa = require('koa');
const Router = require('koa-router');
const api = require('./api');
const app = new Koa();
const router = new Router();
// 라우터 설정
router.use('/api', api.routes()); // add api router
// app instance에 라우터 적용
app.use(router.routes()).use(router.allowedMethods());
app.listen(4000, () => {
console.log('Listening to port 4000');
});
src/api/index.js
const Router = require('koa-router');
const api = new Router();
api.get('/test', ctx => {
ctx.body = 'test 성공';
});
module.exports = api;
src/api/index.js
를 생성하고,src/index.js
에router.use
를 통해 router를 등록해주면 된다.- 이때 주의해야할점은
src/api/index.js
에서 반드시exports
를 해줘야 한다.
posts API 생성하기
src/api/posts/index.js
에 아래와 같이posts
에 관련된 api의 목록들을 정의한다.- 정의한 route를
src/api/index.js
에 적용을 해주면 된다.
src/api/index.js
const Router = require('koa-router');
const posts = require('./posts');
const api = new Router();
api.use('/posts', posts.routes());
module.exports = api;
src/api/posts/index.js
const Router = require('koa-router');
const posts = new Router();
const printInfo = ctx => {
ctx.body = {
method: ctx.method,
path: ctx.path,
params: ctx.params,
};
};
posts.get('/', printInfo);
posts.post('/', printInfo);
posts.get('/:id', printInfo);
posts.delete('/:id', printInfo);
posts.put('/:id', printInfo);
posts.patch('/:id', printInfo);
module.exports = posts;
- 위 같이 정의하고
http://localhost:4000/api/posts/12
을 호출하면 아래와 같은 결과가 나온다.
'Web 개발 > Node' 카테고리의 다른 글
[Node] mongoose, dotenv 을 이용해 Mongodb connection (0) | 2020.02.16 |
---|---|
[Node] Controller 작성하는 코드 예제 (RESTApi 실제 구현부) - POST,GET,DELETE,PUT,UPDATE (0) | 2020.02.16 |
[Node] koa-router 사용방법 parameter, query (예제코드) (0) | 2020.02.16 |
[Node] nodemon을 이용해 서버 자동으로 재시작 (0) | 2020.02.16 |
[Node] async/await 사용예제 코드 (0) | 2020.02.16 |