admin管理员组

文章数量:1296895

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: but I do not want to perform two get requests. How do I acplish this?

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./a/18864738/1703565 but I do not want to perform two get requests. How do I acplish this?

Share Improve this question edited May 23, 2017 at 10:31 CommunityBot 11 silver badge asked Jan 20, 2014 at 21:58 Royston YinkoreRoyston Yinkore 5912 gold badges9 silver badges22 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

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 ment 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.

本文标签: javascriptSend image and JSON data in single NodejsExpress responseStack Overflow