Reputation: 85
I try to draw an image (in base64 format) to a canvas in client-side JavaScript. There is unfortunately always the ERR_CONNECTION_RESET 431 (Request Header Fields Too Large)
error.
I get the base64 image as the response of an async POST request to a Node server. An example base64 image is:
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCA==='
but muuuuch longer obviously. The Chrome Dev console shows this:
GET http://localhost:3000/'data:image/png;base64,iVBORw0KGgoAA...
net::ERR_CONNECTION_RESET 431 (Request Header Fields Too Large)
Image (async)
(anonymous) @ client.js:59
async function (async)
(anonymous) @ client.js:51
My code is:
setInterval(async () => {
const post_options = {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(request)
}
const response = await fetch('/api', post_options)
const result = await response.json()
const base64_response = "'" + result['image64'] + "'"
const image = new Image()
image.onload = () => {
response_ctx.drawImage(image, 0, 0)
}
image.src = base64_response
}, 1000)
where canvas_ctx
is the canvas' 2d context and base64_response
is an image in the above specified format.
I should also mention that I am a newbie to JavaScript and Web Dev, as I only do it for a project of mine.
Upvotes: 6
Views: 13963
Reputation: 16875
image.src
takes a string containing a URL. It looks like you're trying to use a string containing a data URL but you add quotes to the content of that string which makes the URL it contains invalid. The 431 error is the results of the browser trying to make sense of the now broken URL by assuming it's the name of a site-local resource and then requesting it from the server.
To fix this,
const base64_response = "'" + result['image64'] + "'"
should be
const base64_response = result['image64']
Upvotes: 4