Settings
- Node.js 18.12.1
- Koa 2.13.4
Problem
import Router from 'koa-router';
const router = new Router();
router.post('/', async (ctx, next) => {
const result = await YourService.todo();
ctx.body = result;// [200] OK
// ctx.body = '';// [200] OK
// ctx.body = null;// [204] No Content
});
status를 별도 지정하지 않아도, ctx.body의 값에 따라 자동으로 200이나 204로는 바꿔 주는데,
[201] Created 는 찾지 못했습니다.
Solution
...
async function defaultPostResponseMiddleware(ctx, next) {
await next();
if (ctx.body && ctx.status == 200 && ctx.method == 'POST') {
ctx.status = 201;
}
}
app.use(defaultPostResponseMiddleware);
// app.use(router.routes(), router.allowedMethods());
...
router들을 등록하기 전에 middleware를 하나 추가해줬습니다.