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 badges2 Answers
Reset to default 5You 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
版权声明:本文标题:javascript - Send image and JSON data in single Node.js + Express response - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741631722a2389404.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论