I am retrieving an image from a REST API via an HTTP GET with a request body.
I've managed to check the returned content via this test using node.js
and chai.js
:
expect(res).to.have.header('Content-Type', 'image/jpeg');
expect(res).to.have.header('Access-Control-Allow-Origin', '*');
expect(res).to.have.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization');
expect(res).to.have.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
expect(res).to.have.status(200);
expect(res.body).to.be.instanceof(Buffer); // the image content
In the vue.js
file I was used to attach an image to an <img ...>
HTML tag like this:
<img v-bind:src="urlImg">
Then specifying in the javascript part the URL like this:
# this string representing the URL is returned by a function
this.urlImg = 'http://example.com/my_img.jpeg'
but in this case I am not able to provide the URL because the HTTP GET is expecting a body to return the image with content type image/jpeg
.
I am not even sure this is possible and I may be misunderstanding how the content type image/jpeg
is supposed to work. How do I do this in vue.js
? Is it possible at all? Is there a way to check the image content of this HTTP response as with stuff like Postman (Chrome app) I can not inspect the response pretending to treat it as text/Json.
EDIT
Regarding the accepted answer: the last proposed solution (UPDATE 2) worked for me (using HTTP POST providing a JSON body for the request). Make sure you use axios
(https://github.com/axios/axios) to perform the HTTP requests (you can import it in the <script>
part of the Vue file like this: import axios from "axios";
).
I was using vue-resource
(https://github.com/pagekit/vue-resource) pretending it was the same as axios
, but it is not and it took me a while to realize it.
If you already have
Buffer
of your image you can specify pre-defined link in your client app:And define route to send image from server to client (for Express):
Working example for Express+request: My Gist
UPDATE
Load image in browser via ajax (example below). But it is not possible to send request body for GET method with native browser XMLHttpRequest object (this is base for all ajax libraries). From MDN:
UPDATE 2
Decode image as array buffer