Encountering an Issue with Vue.js and Axios when Consuming API: Uncaught TypeError - Unable to Access Property 'protocol' from Undefined

I attempted to consume an API using Axios in VueJS, but encountered an error when trying to fetch data. When I console log(res.data), it throws an error saying "Uncaught (in promise) TypeError: Cannot read property 'protocol' of undefined". Can someone please assist me? It seems like I may have overlooked something.

Here is the code snippet in API.Js file:


import axios from 'axios';
import API from '../API';

var urlLogin = API.url.host + '/login';

var login = {
    init: function(){
        this.vueConfig();
        if(localStorage.getItem('token') != null){
            window.location.replace("./input-mobile.html");
        }
    },
    vueConfig: function(){
        var app = new Vue({
            el: '#app',
            data: {
                isSubmit: false,
                email: "email",
                password: "password",
            },
            methods: {
                submitLogin: function(){
                    this.isSubmit = true;
                    axios.post()
                    axios({
                        method: 'post',
                        url: urlLogin,
                        data: {
                            email: this.email,
                            password: this.password
                        }
                    }).then(res =>{
                        console.log(res.data);
                        this.isSubmit = false;
                        localStorage.setItem("token", res.data.access_token);
                        localStorage.setItem("name", res.data.fullname);
                        window.location.replace("./input-mobile.html");
                    }, err =>{
                        console.log(err);
                        this.isSubmit = false;
                    });
                }
            }
        });
    }
}

module.exports = login;

The API appears to be functioning correctly as it gives the correct response in the network tab (inspect) of the browser. However, there seems to be a problem with fetching the data.

Answer №1

Your Axios callback is referring to the wrong object. To fix this, try starting your submit method with let self = this, and then replace this.isSubmit with self.isSubmit in your callback.

submitLogin: function(){
  let self = this;
  this.isSubmit = true;
  axios({
     method: 'post',
     url: urlLogin,
     data: {
         email: this.email,
         password: this.password
     }
  }).then(res =>{
     console.log(res.data);
     self.isSubmit = false;
     localStorage.setItem("token", res.data.access_token);
     localStorage.setItem("name", res.data.fullname);
     window.location.replace("./input-mobile.html");
  }, err =>{
     console.log(err);
     self.isSubmit = false;
  });
}

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

Tips on resolving the Hydration error in localStorage while using Next.js

Having issues persisting context using localStorage in a Next.js project, resulting in hydration error upon page refresh. Any ideas on how to resolve this issue? type AppState = { name: string; salary: number; info: { email: string; departme ...

Preparing the data for populating Google charts

I am attempting to showcase Line charts using the Google API. I have tried to format the data from an ASP.net Webmethod as shown below: [WebMethod] public static List<object> GetChartData() { List<object> chartData = new List<obj ...

difficulty encountered when using the Angular delete method in conjunction with Express.js

I am trying to send a delete request to my Express server from Angular. remove: function (id) { return $http({ method: 'DELETE', url: '/users/delete/'+ id }) } In my Expr ...

Converting an object with a combination of different index types into a string representation

I'm dealing with a unique object structure that behaves similarly to an array, except it contains a mix of index types (numbers and strings). Here's an example: var myObj = []; myObj[0] = 'a'; myObj[1] = 'b'; myObj[2] = &apos ...

"Displaying the y-axis in d3.js: A Step-by-Step

I am a beginner in d3.js and I'm having trouble with my y-axis not showing up in the browser. Can someone please help me find a solution? var barOffset=5; var barWidth=50; var width=700,height=700; function processData(data,key){ var objects=[]; ...

Any suggestions on how to address vulnerabilities in npm when upgrading the main dependency version is not an option?

I recently ran the npm audit --production command and found a high-risk vulnerability related to the snowflake-sdk dependency. After checking the snowflake github page, I noticed that the package.json file includes "requestretry": "^6.0.0&qu ...

Issues with concealing the side menu bar in Vue.js

I've been attempting to conceal the side menu bar, with the exception of the hamburger icon when in the "expanded" state. Despite my efforts to modify the CSS code, I am still struggling to hide the small side menu bar. The following images represent ...

Integrate a loading screen on the website

Check out the awesome animation I created! Can this be used as a preloader on my website? Should I stick to creating a simple .gif or opt for a CSS animation instead? If it’s feasible, how do I go about integrating it into my site? Most tutorials suggest ...

What is the process for modifying a Date type value in JavaScript?

I'm looking to create a graph that illustrates the sun's altitude throughout the day, resembling a sine curve. Users should be able to input a location (latitude & longitude) and a date, and the graph will adjust accordingly. I've incorpora ...

Despite being logged, the current value of firebase.auth().currentUser in Firebase is null

I have coded a query in my service.TS file that displays the "state" of items based on the UID of the logged-in user: getLists(): FirebaseListObservable<any> { firebase.auth().onAuthStateChanged(function(user) { if (user) {console.log("blah", fir ...

Issue with authentication when accessing Google Video API

I'm attempting to utilize the Google API provided: I have downloaded the Sample Project and followed these steps: 1) Navigate to the Project Folder named API Video 2) Run npm install 3) Set GCLOUD_PROJECT = neorisvideo 4) Download Json from the C ...

JavaScript file does not execute onload function

Whenever I try to execute the window.onload function from my .js file, it seems to not be firing as expected. <script type="text/javascript" src="{% static 'jsfile.js' %}"></script> window.onload = function() { alert(' ...

Breaking down a div with jQuery - tips and tricks!

I have a question regarding jQuery. Consider the following structure: <div class="page"> <p>Lorem ipsum....</p> <p>Lorem ipsum....</p> ... </div> I want to transform it into this format: <div class="pa ...

Tips for effectively overlaying one container on top of another in a responsive manner

There are a pair of containers. The main container functions as the parent, while the child container acts as a tag to categorize the content. The objective is to position the tag container at the top right corner of the main content container, slightly of ...

display images fetched from a PHP/MySQL database in a jQuery dialog box

UPDATE: A solution has been found and the code has been updated accordingly. Currently, I have the images stored in a directory on my local system where I am hosting an IIS server. I am able to retrieve these images successfully and display them using the ...

Tips for presenting HTML source code with appropriate tag coloring, style, and indentation similar to that found in editors

I need to display the source code of an HTML file that is rendered in an iframe. The source code should be shown with proper tag colors and indentations similar to editors like Sublime Text. https://i.stack.imgur.com/IbHr0.png I managed to extract the sour ...

Vue throwing ReferenceError when accessing uninitialized variable in Safari browser

Recently, I've encountered a perplexing error message that has me scratching my head. The error message reads as follows: ReferenceError: Cannot access uninitialized variable. This error specifically points to the line of code: const app = createApp(A ...

Enhance data granularity in Jquery Flot by zooming in as the user interacts

I'm currently working on creating an interactive chart that allows users to zoom in for a more detailed view of the data. For instance, when viewing data over a default zoom period of 3 months, there would be one data point displayed every 24 hours. H ...

Having trouble resolving the signature of a class decorator when invoked as an expression with @Injectable in Angular

Error Message: Unable to resolve the signature of a class decorator when called as an expression. The argument type 'ClassDecoratorContext' is not compatible with the parameter type 'string | symbol | undefined'. After creating a book ...

Vuejs and Nodejs are not providing the necessary 'Access-Control-Allow-Origin' header on the requested resource

What could be causing the error in my code? app.use(function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-M ...