HTTP error 431 when trying to draw a base64 image to a canvas
Asked Answered
R

1

6

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.

Rizzo answered 11/12, 2019 at 17:17 Comment(0)
G
4

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']
Grieve answered 11/12, 2019 at 20:21 Comment(2)
I tried this before actually, it instead throws the error: net::ERR_INVALID_URL. The URL is just http://localhost:3000/data:image/png;base64,iVB... then, do you know why that is invalid?Rizzo
Ok, I have found the problem: My backend server didn't have correct = padding at the end of the base64 string. I just traded one error for another.Rizzo

© 2022 - 2024 — McMap. All rights reserved.