3

I am creating a web API with Node.js and Express and intend to use a single response to return an image and JSON data simultaneously. I saw a solution to specify headers: https://stackoverflow.com/a/18864738/1703565 but I do not want to perform two get requests. How do I accomplish this?

Community
  • 1
  • 1
Royston Yinkore
  • 561
  • 1
  • 8
  • 22

2 Answers2

4

You could encode the image as a base64 string (http://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end), and return this as part of your JSON.

Kevin Schmid
  • 741
  • 5
  • 9
2

Cookies

You could return the image as a normal image response body and then set a session cookie with the same request. The session cookie would contain the JSON data. Once the image loads you can pull the JSON data from the cookie via javascript.

This would work in all browsers. Only limitation would be the size of the JSON you could return. Max size looks to be 4093 bytes.

Image Encoding

If your JSON is too big to fit in a cookie then you could encode the image as a base64 object and return the image data in the JSON response.

In this case you would have to reconstruct the image on a canvas or use the image data url format to dynamically create an image object as the url in the comment from Kevin does.

One downside to image encoding would be the increased size of the response. Roughly, the size of the image after encoding in base64 would be 37% larger than the original image.


Ultimately it depends on your specific needs as to which method would best fit your requirements.

Community
  • 1
  • 1
Daniel
  • 38,041
  • 11
  • 92
  • 73
  • You would not have to reconstruct the image on a canvas. See http://www.bigfastblog.com/embed-base64-encoded-images-inline-in-html – Kevin Schmid Jan 20 '14 at 22:13
  • The first option would not work for me as this is purely a web API consumed by mobile apps. The second option didn't even occur to me...lol. Thanks a lot. However, are you positive this is the absolute best method for this? – Royston Yinkore Jan 20 '14 at 22:40
  • @Daniel thank you very much, I've gotten a solution to my problem. I do not have to send the image and data together. I can send the URL of the image in the JSON so the client can download it. Cheers – Royston Yinkore Jan 20 '14 at 22:47