site is https://unruffled-jang-4961e9.netlify.app/
This aggregates a bunch of feeds including a bunch of images hosted on various other sites. Some of those images come through fine using a naive fetch from the frontend, but others run into CORS issues along the way, so trying to set up a proxy.
Carefully followed through this article Solve CORS once and for all with Netlify Dev
I got that to work as far as how it’s proxying some JSON.
But in this case I just have binary data coming back. I got slightly different results when setting the isBase64Encoded
property on the function handler’s result.
Seems like I can base64 encode the original response data and return that instead of setting isBase64Encoded
true.
I’m not sure it makes much difference, though.
On the frontend, I found one example showing how to set an img
by response data, and in that case the author used this data,
const testByteArray = new Uint8Array([
137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,8,0,0,
0,8,8,2,0,0,0,75,109,41,220,0,0,0,34,73,68,65,84,8,215,99,120,
173,168,135,21,49,0,241,255,15,90,104,8,33,129,83,7,97,163,136,
214,129,93,2,43,2,0,181,31,90,179,225,252,176,37,0,0,0,0,73,69,
78,68,174,66,96,130])
That works fine when substituted for the live function response. Something about the encoding I’m not tracking correctly while processing it on the frontend.
For the netlify function I have:
const response = await fetch(foreignUrl)
if (!response.ok) {
return {
statusCode: 502,
body: 'Bad Gateway'
}
}
else {
const buffer = await response.buffer()
return {
body: buffer.toString('base64'),
isBase64Encoded: true,
statusCode: 200,
}
}
Then in the frontend I have:
return axios.get(proxyUrl).then(
response => {
const data = response.data
console.log('data', data)
// const testByteArray = new Uint8Array([
// 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,8,0,0,
// 0,8,8,2,0,0,0,75,109,41,220,0,0,0,34,73,68,65,84,8,215,99,120,
// 173,168,135,21,49,0,241,255,15,90,104,8,33,129,83,7,97,163,136,
// 214,129,93,2,43,2,0,181,31,90,179,225,252,176,37,0,0,0,0,73,69,
// 78,68,174,66,96,130])
const byteArray = (new TextEncoder()).encode(data)
console.log(byteArray)
return new Blob([byteArray], {type: 'image/png'})
}
The dump of the response.data
looks like e.g. �PNGIHDR���)�tEXtSoftware Adobe Image Readyq�e< ...
(lots of characters don’t copy into here but looks like this)
The dump of the byteArray
looks like e.g. Uint8Array(428297) [239, 191, 189, 80, 78, 71, 13, 10, ...
I get a broken <img/>
when setting the img
with this src={URL.createObjectURL(blob)}
.
However like I said if I switch out the testByteArray
I get the test image showing up no problem.
So something in all this encoding/decoding utf-8, etc, has gone wrong, although it seems like it’s almost there.