How to show the raw image content-type using Vue.js

When retrieving an image from a REST API through an HTTP GET with a request body, I have successfully verified the returned content 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 my vue.js file, I typically attach an image to an <img ...> HTML tag as follows:

<img v-bind:src="urlImg">

I specify the URL in the JavaScript part like this:

# The URL string is returned by a function
this.urlImg = 'http://example.com/my_img.jpeg' 

However, in this scenario, providing the URL is not possible because the HTTP GET expects a body to return the image with content type image/jpeg.

I am unsure if this is feasible and if my understanding of the content type image/jpeg is correct. How can I accomplish this in vue.js? Is it even doable? Is there a way to check the image content of the HTTP response similar to tools like Postman (Chrome app) which cannot inspect the response pretending to treat it as text/JSON.

EDIT

Regarding the accepted answer: the last solution proposed (UPDATE 2) worked for me (using HTTP POST with a JSON body for the request). Ensure you utilize axios (https://github.com/axios/axios) for performing the HTTP requests (you can import it in the <script> section of the Vue file like this: import axios from "axios";).

I initially used vue-resource (https://github.com/pagekit/vue-resource) thinking it was similar to axios, but it took some time for me to realize that they are different.

Answer №1

If you have a pre-defined Buffer for your image, you can set a specific link in your client app:

this.urlImg = '/my/url/to/get/dynamic/image';

To send the image from the server to the client (using Express), define the route as follows:

server.get("my/url/to/get/dynamic/image", function(req, res) {
   var myBuffer = yourFunctionReturnsBuffer();
   res.writeHead(200, {
    'Content-Type': 'image/jpeg',
    'Content-Length': myBuffer.length
   });
   res.end(myBuffer); 
 });

Here is a working example for Express+request: My Gist

UPDATE

You can load an image in the browser via AJAX. However, it's not possible to send request body for the GET method with the native browser XMLHttpRequest object according to MDN:

send() accepts an optional parameter that lets you specify the request's body; this is primarily used for requests like PUT. If the request method is GET or HEAD, the body parameter is ignored and request body is set to null.

var app = new Vue({
    el: "#app",
    data: {
        src: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
    },
    created() {
        let config = {
            url: 'https://www.gravatar.com/avatar/7ad5ab35f81ff2a439baf00829ee6a23',
            method: 'GET',
            responseType: 'blob'
        }
        axios(config)
          .then((response) => {
              let reader = new FileReader();
              reader.readAsDataURL(response.data); 
              reader.onload = () => {
                  this.src = reader.result;
              }
          });
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <img :src="src" alt="">
</div>

UPDATE 2

Decoding an image as an array buffer

var app = new Vue({
    el: "#app",
    data: {
        src: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
    },
    created() {
        let config = {
            url: 'https://www.gravatar.com/avatar/7ad5ab35f81ff2a439baf00829ee6a23',
            method: 'GET',
            responseType: 'arraybuffer'
        }
        axios(config)
          .then((response) => {
              var bytes = new Uint8Array(response.data);
              var binary = bytes.reduce((data, b) => data += String.fromCharCode(b), '');
              this.src = "data:image/jpeg;base64," + btoa(binary);
          });
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <img :src="src" alt="">
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to remove an object element by index within AngularJS?

One of my challenges involves dealing with objects, specifically $scope.formData = {} I am trying to figure out how to remove an element from the object using the index $index: $scope.formData.university[$index]; My attempt was: $scope.formData.univer ...

The request to sign up at http://localhost:3000/api/signup resulted in a 400 (Bad Request

Having recently started working with the MEAN stack, I've run into some issues when trying to send registration data using http.post. Below is my server code: var express = require('express'), bodyParser = require('body-parser' ...

What could be causing my insertRow function to inject empty cells into my table?

I am facing an issue with adding the results of a fetch request into a table as a new row. Strangely, when I click the button to trigger this function for the first time, it adds an empty row instead of the desired data. However, on subsequent clicks, the ...

Exploring through a dynamically generated table containing JSON data

I have successfully implemented a dynamic HTML table that is populated with JSON data based on the value of a variable when the "go" button is clicked. The initial population and search functionality work flawlessly. However, I encountered an issue when ch ...

The rendering of the component is experiencing issues when using react-router

function App() { return ( //Following BEM naming convention <div className="app"> <div className="app__body"> <Sidebar /> <Chat /> <Router> <Routes> ...

Is there a way to customize the ripple effect color on a Button?

As I'm exploring the API (v3.9.2), I have noticed a reference to TouchRippleProps for ButtonBase on https://material-ui.com/api/button-base/ The code for my button is as follows: <Button variant="text" size={"large"} ...

function to choose in antd datepicker component

Is there a way to obtain the currently selected date within the onSelect function after updating the selected date in the state? onSelect = (cal) => { this.setState({ selectedValue: cal }); alert(this.state.selectedValue); After making ...

Exploring the depths of object properties with Angular, JavaScript, and TypeScript: A recursive journey

Let's consider an object that looks like this: const person = { id: 1, name: 'Emily', age: 28, family: { mother: { id: 101, name: 'Diana', age: 55 }, fathe ...

Tips for navigating a list of areas in JavaScript

Currently, I am in the process of learning Javascript and I have a query regarding browsing an area list using Javascript. Could someone kindly guide me on whether it is possible to achieve this, and if so, how? Below is the HTML code snippet I am workin ...

Surprising outcome arising from simultaneous execution of numerous asynchronous operations on every individual object within an array

I'm fairly new to working with Node.js and I'm still trying to grasp the concept of callbacks and the asynchronous nature of Node.js. However, I've encountered a problem that I can't seem to solve. I've already searched extensively ...

Why is my Ajax utilizing PHP _POST not functioning as expected?

I am facing an issue with the JavaScript code below: <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js'></script> <script> function deletUserInfo(id_user){ console.log(id_user); ...

Error encountered while making a REST API call in Ajax: Unforeseen SyntaxError: Colon unexpected

I am currently troubleshooting my code to interact with a REST API. My platform of choice is "EspoCRM" and I aim to utilize its API functionalities. The official documentation recommends using Basic Authentication in this format: "Authorization: Basic " ...

initiating a submission upon the occurrence of an onchange event on an input field of type "file"

I have encountered an issue while trying to submit a form using the onchange event of an input element with type file. The problem is that it submits an empty form even when a file has been chosen. Here is the code snippet: var form = document.createElem ...

Dealing with a syntax error in JavaScript (Codecademy)

I have been working my way through the JavaScript course on Codeacademy and for the most part, I've been able to figure things out on my own. However, I've hit a roadblock with my code and can't seem to get it right. Here is the code I&apos ...

I'm looking for a solution to implement a vertical carousel in Google's Materialize CSS without the need for custom development

Looking to create a unique vertical scrolling "carousel" using Google's Materialize CSS library. I have a good understanding of the steps required to construct a carousel. # haml %ul.carousel %li.carousel-item Some Content %li.carousel-item ...

Attempting to establish a connection with MongoDB through Realm

Exploring Realm and MongoDB for the first time has been an interesting journey for me. I began by following a helpful tutorial as a starting point for my project. Here is the link to my project structure on CodeSandbox The folder structure includes: src ...

modify the getters in the Vuex store

As I attempt to modify the data retrieved using getters, I find myself creating a dynamic form for editing values. While I can display the data successfully, I am still uncertain about how to update the data using getters. This is my edit form: You can a ...

The issue I am encountering is that the value from jQuery autocomplete is not getting transferred to the

I'm having trouble retrieving a textInput from a Form where I am extracting values from Jquery Autocomplete. The selected value is not being transferred to the form. Can you please help me identify what I am missing? $(function() { var availableT ...

Having trouble finishing the npm installation process

Having trouble with completing 'npm install'. Can someone please assist me?</p> <pre><code>Encountering a warning about an old lockfile while running npm install. The package-lock.json file was created with an outdated version o ...

DOJO Dialogue Box Report - Problem

I'm currently facing a challenge with incorporating javascript into the dialog box of my application. Here is an example of the code I am struggling with - var profileDialog1 = new Dialog({ title: "Create Profile", style: "width: 700px;he ...