はじめに
ルー大柴ぽいのが否めませんが表題の通りです。
訳あってBFF(Backend For Frontend)を採用する必要があり、クライアントサーバーとバックエンドサーバーでのやりとりで詰まったのでメモを残します。
※個人の見解です。明確なエビデンスを探し切ることができませんでした。根拠が乏しいので、真に受けないことをおすすめします。
背景
バックエンドサーバーから画像を取得しようとしたら次のようなレスポンスがクライアントサーバーに返ってきた。
結論
サーバー側でaxiosを使って画像をgetする時はresponseTypeをarrayBufferにする必要があるらしい。
引用①(axiosのドキュメントを引用している)
how does axios handle blob vs arraybuffer as responseType , From axios docs: // responseType indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', You can configure the type of the dataproperty using Axios' responseTypeobject. responseTypeis set to 'json', which means Axios will try to parse the response as JSON. However, that isn't correct if you're looking to, say, download an image using Axios. You can set responseTypeto 'arraybuffer'to get the response as an ArrayBuffer:
引用②
You can configure the type of the data property using Axios' responseType object. By default, responseType is set to 'json', which means Axios will try to parse the response as JSON. However, that isn't correct if you're looking to, say, download an image using Axios. You can set responseType to 'arraybuffer' to get the response as an ArrayBuffer:
サーバー側でaxiosを使っていて画像のやりとりをするときはresponseがarrayBufferで指定して受け取らないと文字化けしてしまう。とのことで、クライアント⇄サーバーの経験はあってもサーバー⇄サーバーは未経験でしたので解決までに時間がかかりました。次の記事は今回はまったのと同じ状況だったのと図解もされているので非常に参考になりました。
axiosでarrayBufferを使うとき
const axios = require('axios');
const res = await axios.get('https://images.unsplash.com/photo-1506812574058-fc75fa93fead', {
responseType: 'arraybuffer'
});
const fs = require('fs');
fs.writeFileSync('./south-beach.jpg', res.data);
axiosでarrayBufferを使わないとき
const axios = require('axios');
const res = await axios.get('https://httpbin.org/get', { params: { answer: 42 } });
res.headers['content-type']; // 'application/json'
const axios = require('axios');
const res = await axios.get('https://httpbin.org/html');
res.headers['content-type']; // 'text/html; charset=utf-8'
typeof res.data; // 'string'
res.data; // '... <h1>Herman Melville - Moby-Dick</h1> ...'
さいごに
BFFで検索するとズッ友の方が出てくるあたりまだユースケースは少ないのかなと思いました。が、有名企業が採用していることもあるのでBFFを採用するところはこれから増えてくるような気がします。もしクライアントサーバーからaxiosを使って画像情報のやりとりをする際はarrayBufferを使うことを念頭に置くと良いと思います。