Utilizing Vue.js to convert blobs into objects or strings and assign them to application variables

I am currently working on a Vue app and have the following setup:

data: function() {
    return {
        modules: [],
        ...

Along with the following method:

methods: {
    submitted: function(){
        ...
        axios({method: 'get',
              url: 'http://' + document.location.host + '/api/execute?commands=' + encodeURI(JSON.stringify(commands)),
              responseType: "blob"}).then(response => {
            
            if (response.headers['content-type'] === 'image/jpeg'){
                this.modules[current]['results']['image']['visible'] = true
                this.modules[current]['results']['text']['visible'] = false
                
                const url = window.URL.createObjectURL(response.data)
                this.modules[current]['results']['image']['value'] = url
            }
            else{
                this.modules[current]['results']['image']['visible'] = false
                this.modules[current]['results']['text']['visible'] = true
                var reader = new FileReader();
                reader.onload = function(e) {
                   // reader.result contains the contents of blob as a typed array
                   console.log(e)
                   this.modules[current]['results']['text']['value'] = reader.result
                }
                reader.readAsArrayBuffer(response.data);
                
            }
            ...

This piece of code is responsible for fetching data from a server and displaying it as text or image based on the server's response.

*v-for module in modules earlier*
<div class="resultText" :visibility=module.results.text.visible>
    {{ module.results.text.value }}
</div>
<div class="resultImage" :visibility=module.results.image.visible>
    <img :src=module.results.image.value>
</div>

However, I encounter a JavaScript error when the server returns text: TypeError: this.modules is undefined
The error seems to be occurring in this part of the code:

this.modules[current]['results']['text']['value'] = reader.result

The method works correctly with images, but when dealing with text it throws the same error: TypeError: self.modules is undefined

Answer №1

Successfully resolved the issue using the following code snippet:

response.data.text().then(text => {
    this.modules[current]['results']['text']['value'] = text
});

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

Is there a way to convert time measurements like minutes, hours, or days into seconds in React and then pass that information to an

Currently, I am working on an application that allows users to select a frequency unit (like seconds, minutes, hours, or days) and input the corresponding value. The challenge arises when I need to convert this value into seconds before sending it to the ...

Unable to deploy Worker-Loader alongside Vuejs and Webpack

Having some difficulties setting up web workers with Vue cli3. I prefer using the worker-loader package over vue-worker due to its maintenance and contributions. Following the instructions provided by worker-loader, I tried adjusting webpack using vue cli ...

Exploring alternative font options in Three.js for a unique visual experience

For my current project, I am working with three.js and I am interested in using a font other than the default "helvetiker". After some research, I learned that I need to convert the font using typeface.js to obtain a font file. I have successfully converte ...

What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code: Html: <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/> <input type='file' (change)="onSelec ...

Signal check indicates that the Internet connection has been restored

One of the key requirements for my app is to load data into a database, which necessitates having an active Internet connection. I have been contemplating what to do in case of network failure - perhaps I can store the data locally on the device and synch ...

It seems like Passport.js signup functionality is functioning properly, however, the user information is not being stored in

After referencing resources from Scotch.io and the official passport docs, I am in the process of incorporating a Node/Express/Sequelize application. The main feature I am working on is a simple signup form that includes fields for email and password: ./v ...

Axios issue: Cookies are not being transmitted

I have encountered an issue with a form built on Nuxt/vuejs and the backend side on django where CSRF protection is enabled. The API call now requires two things: X-CSRFToken as a header and csrftoken as a Cookie. I tested the API using Postman and it work ...

Cannot designate Vue setup function as asynchronous

I have a Vue3 application using the composition api and I am trying to fetch data asynchronously within the setup function. Here are two approaches that have successfully worked for me: Approach 1: Working with Promises <template> <div ...

Is there a way to identify the moment when a dynamically added element has finished loading?

Edit: I've included Handlebar template loading in my code now. I've been attempting to identify when an element that has been dynamically added (from a handlebars template) finishes loading, but unfortunately, the event doesn't seem to trig ...

Storing the path of a nested JSON object in a variable using recursion

Can the "path" of a JSON object be saved to a variable? For example, if we have the following: var obj = {"Mattress": { "productDelivered": "Arranged by Retailer", "productAge": { "ye ...

Could not find reference to Google (error occurred following ajax request)

I encountered an error message when attempting to use the Google Map after making an ajax call. ReferenceError: google is not defined The issue arises when I include the link "<script type="text/javascript" src="http://maps.google.com/maps/api/js?sen ...

What is the method for displaying a view in AngularJS using the ui-view directive?

I am attempting to load my first view using ui-view, however I am not receiving any errors but the view is not displaying. Here is the link to my Plunker for reference: http://plnkr.co/edit/kXJV11B0Bi8XV2nwMXLt (function() { 'use strict'; ...

Utilizing Azure Mobile Services with HTML

Is there a way to integrate my Windows Azure Mobile Services into an HTML page? I attempted to utilize the code snippets provided in the Azure portal, but unfortunately, they did not work for me. The prescribed code snippets that need to be included in m ...

Leverage - Utilize the object sent through the render method in an external JavaScript file

In my index.js file, I am sending an object from Express using the render function like this: app.get("/chat", function(req, res){ res.render("chat", {user: req.user}); }); The object can be utilized in my chat.ejs file: <% if(!user){ %> <l ...

How to efficiently iterate through an array in Nuxt using a v-for directive and effectively display the data

I am struggling with looping through nested data from a JSON file on my e-commerce website. Despite trying several methods, I have not been successful in achieving this. async fetch() { this.post = await fetch( `http://test.com/api.php?id=${this. ...

Dynamic CSS Class Implementation with KnockoutJS

Greetings, I am seeking assistance as I am new to KnockoutJS. I am working with a class named green-bar that I need to activate when two particular states are true. Unfortunately, the solution I came up with below is not functioning correctly, and I'm ...

Gather all information for populating the dropdown menu

I'm trying to fetch data from an API using Vue Form and Axios, but I'm having trouble retrieving it at the moment. I might have missed something. Specifically, I need to retrieve the brand of a car. When a brand is selected in one dropdown, the s ...

Activate dual AJAX JSON and cycle through multiple alerts each time an "ul li" element is clicked

In my code, I am utilizing two ajax requests. One retrieves a chat userlist column in JSON format, while the other fetches the message history for each user. The functionality works such that when a $('.member_list ul li') element is clicked, th ...

Exploring the structure and dispersion of files within a VueJS project: An architectural inquiry

As I delve into learning VueJS, I've come to understand that .vue files typically consist of three distinct parts: <template>, <script>, and <style>. My query pertains to how these three parts are managed in a professional VueJs pro ...

JavaScript's getElementsByName() method allows for easy access and

Excuse my lack of experience... I am attempting to run a javascript using the getElementByName method, with the goal of entering 0 in the quantity field on a particular site after 15 seconds of arriving there. Upon inspecting the quantity field, here is w ...