3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

axios 0.21.2で二重JSON.stringifyバグ? → 0.21.4で修正

Posted at

Node.js およびブラウザ向けの XHR ライブラリ axios のバージョン 0.21.2 で、アプリ側の実装によって発生するバグないし breaking change が入ってしまい、近日公開の 0.21.4 で修正される見込みです。→ 修正PR

axios で POST するとき、典型的には以下のように使います。

const axios = require("axios");

const data = {"id": 123};

await axios.post("/api", data); // OK

上記は下記と同じ意味であり、これについては 0.21.2 でも問題ありません。

await axios.post("/api", data, {headers: {"content-type": "application/json"}}); // OK

しかし、事前にボディを文字列化していた場合に従来との挙動が変わっていました。

const json = JSON.stringify(data);

await axios.post("/api", json); // NG

await axios.post("/api", json, {headers: {"content-type": "application/json"}}); // NG

0.21.1 以前では、上記で {"id": 123} という文字列がそのまま送信されていたところ、
0.21.2 では二重に JSON.stringify 変換された "{\"id\":123}" という文字列が送信され、
API サーバ側で展開エラーが起きていました。この問題は 0.21.4 で直る見込みです。

ただし、今後は事前に stringify したい場合は、下記のほうが安全で速いかもしれません。

const buffer = Buffer.from(JSON.stringify(data));

await axios.post("/api", buffer, {headers: {"content-type": "application/json"}}); // OK

個人的には、余計なことせずに、シンプルなままで保って欲しいが。

3
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?