症状
koaで構築したサーバーにファイルをアップロードしたら、koaが以下のようなエラーを吐いた。
Error: request entity too large
丁度画像をアップロードする機能を作っていたので、ある意味想定内。
調査
調べてみると、express関連のStack Overflowからヒントを得られる。
Node JS - Express Request entity too large
I had the same error recently, and all the solutions I've found did not work.
After some digging, I found that setting app.use(express.bodyParser({limit: '50mb'})); did set the limit correctly.
bodyParserで設定するrequest bodyの上限値に引っかかっている模様。
今回koaで作っているプロジェクトでは、koajs/bodyparserを使っているので、以下2つのoptionで設定可能。
formLimit: limit of the urlencoded body. If the body ends up being larger than this limit, a 413 error code is returned. Default is 56kb
jsonLimit: limit of the json body. Default is 1mb
対応
JSON bodyの上限値は1mbもあれば十分な気がするが、formLimitは画像などの大物を許容するには少ない。そのため、以下のように修正。
app.use(bodyParser({
formLimit: '512kb'
}));
以上でエラーは起きなくなった。
koaは多くの点でexpressと互換しているので、トラブルが起きた際も解放がすぐ見つけやすい。