Retrieve the Axios response without interruption, even in the event of an exception, when making API calls with multiple files

Currently, as a beginner diving into Vue.js, I am exploring the world of frontend development by integrating Vue with my Laravel backend. To streamline my API calls and make them more organized for different models, I decided to create a separate file named api.js, housing a simplistic API class.

The contents of api.js:

export default class API {
    static async invoke(url, method, data=null, headers=null, acceptJson=true){
        headers = headers || {}
        if(acceptJson){
            headers['Accept'] = 'application/json';
        }
        try{
            return axios({
                method: method,
                url: url,
                data: data,
                headers: headers
            });
        }
        catch(e){
            console.log("Something went wrong while connecting to the server.");
        }
    }
}

To utilize this function effectively, I structured my code by creating a dedicated folder named models. Each model, such as User.js and Activity.js, has its own JS file within this folder.

The content of User.js:

import API from '../api';

export default class User {
    /**
     * Login user to the system
     *
     * @param username string
     * @param password string
     */
    static async login(username, password){
        return await API.invoke('/api/login', 'POST', {
            'email': username,
            'password': password
        });
    }
  }

I called this method within my Login.vue component.

The SignIn method in Login.vue:

async signIn(){
    try{
        const response = await User.login(this.username, this.password);
        if(response.status === 200){
            this.$router.push('/dashboard');
        }
    }
    catch(err){
        this.loginError = err.response.data.message;
    }
}

My directory structure looks like this:

js
│   api.js
│   app.js
│   bootstrap.js
│   router.js
│   
├───components
│   │   App.vue
│   │   
│   └───pages
│           Activities.vue
│           Login.vue
│           Main.vue
│           Settings.vue
│
└───models
        User.js

Everything functions smoothly when the credentials are correct. However, Axios throws exceptions when there's an error, preventing me from accessing error messages in Login.vue. How can I restructure my code to display backend errors in components while keeping the API call codes separated in different files?

I created this code structure based on some research and personal experience. Any suggestions for improving the organization of these codes would be greatly appreciated!

Answer №1

The overall structure appears to be solid.

When it comes to the Login.vue component, instead of having separate try and catch blocks, you could consider implementing the following approach:


 signIn(){
     User.login(this.Username, this.password)
      .then((response) => {
       if(response.status === 200)
         this.$router.push('/dashboard');
      })
      .catch((err)=>{
        this.loginError = err.response.data.message
      })
}

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

Ways to retrieve the neighboring element's value and modify it with the help of JavaScript or jQuery

I am encountering a problem with selecting an adjacent element and updating its value. My goal is to update the input value by clicking the minus or plus buttons. I have successfully retrieved all the buttons and iterated through them, adding onclick eve ...

Configuring properties for a component by retrieving data from MongoDB using an API request

My current API call utilizes axios in the following format: Service.get('path/to/api', (status, data) => { this.setState({ ComponentData: data, loaded: true}); }); {this.state.loaded && <Component id={this.state.ComponentD ...

Is it possible to achieve seamless image transitions in Firefox like it does in Chrome?

To achieve the desired effect, you may need to use some javascript. Visit aditagarwal.com for more information. Styling with CSS: .images-wrapper{ position: fixed; left: 0; top: 80px; bottom: 0; width: 100%; height: 100vh; an ...

Improving functions in vue.js

Currently working on my personal project, which is an HTML website containing tables generated through vue.js. I believe that my code could be simplified by refactoring it, but I am unsure about where and what changes to make. Below is the section of the c ...

Troubleshooting issue: Django and Javascript - Why is my dependent dropdown feature not

I am new to using a combination of Javascript and Django. Below is the script I have written: <script> $(document).ready(function() { $("#source").change(function() { var el = $(this); var reg = ...

Error encountered when trying to access the _id property in React Components using MongoDB and passing a Key: TypeError - Property _id is undefined

I've encountered an issue when trying to pass a field from MongoDB into a React Component. Here is the snippet of code I'm working with: import React from 'react'; import ReactDOM from 'react-dom'; import { Meteor } from &apo ...

Linking asynchronous functions does not function properly

I've been attempting to link two asynchronous functions together, but it appears that the second function is running before the first one. Below is the code snippet: function performAction(e) { const ZIP = document.getElementById('zip').valu ...

JavaScript: The functionality of calling functions through buttons ceases to function once the page is updated without reloading

I am trying to create a program that consists of one HTML page, where I can dynamically update and populate it with different elements using JavaScript. The main feature of the program is a button that remains constant in every version and displays a mod ...

Converting a string to a number, even if it contains non-numeric

Is there a built-in function that can directly convert a string containing non-numeric characters to a number in JavaScript, without the need for using str.substring() followed by parseInt()? For instance, how can I efficiently convert the string x1 to th ...

Disable the resizing and responsiveness features in the jQuery Basic Slider

I'm currently utilizing the Basic jQuery Slider from the Basic Slider website, and I am attempting to eliminate the responsive/resize feature. My goal is to keep the slider contained within a centered div without changing its size. However, whenever I ...

When a URL is entered, information is not retrieved from the database

I have a simple app setup where the data (iPhones from the database) is fetched in the AppComponent itself. ngOnInit(): void { this.iphoneservice.fetchIphones(); } The fetchIphones method is located in my iPhoneService file and consists of 3 functio ...

Is it possible to create an AngularJS and jQuery Calendar Directive that activates by clicking on a Bootstrap glyphicon?

I have successfully created a directive for my calendar using AngularJS and jQuery. The datepicker pops up when the user selects the input box. Now, I am attempting to allow the user to click on Bootstrap's 'glyphicon glyphicon-calendar' to ...

Adding colors to your Vue3 and Vuetify3 theme: A Step-by-Step Guide

Currently, I am in the process of upgrading an old Vue2 app to Vue3 and I have a specific requirement to set up 3 global colors: red, green, and gray. In order to achieve this, I am implementing the following code snippet within my vuetify.js file: // Styl ...

Creating a randomly generated array within a Reactjs application

Every time a user clicks a button in reactjs, I want to create a random array of a specific size. The code for generating the array looks like this: const generateArray = (arraySize: number): number[] => { return [...Array(arraySize)].map(() => ~~( ...

Error encountered during Yarn installation process: The tunneling socket was unable to be established due to a connection refusal on localhost at port 80

I have a Next.js app that needs to be built on our company servers before deployment. We use a proxy, and I've configured yarn to use the proxy as well. yarn config set proxy http://xx.xxx.xx:xxxx yarn config set httpsProxy http://xx.xxx.xx:xxxx yarn ...

The table headers in the second table do not match the queryAllSelector

I've encountered an issue with my JavaScript snippet that displays a responsive table. When I use the snippet for a second table with the same class, the formatting gets messed up on mobile devices (try resizing your screen to see). It seems like the ...

Tips for preloading a small placeholder image before the main content is loaded

After browsing , I noticed an interesting image loading style. The website initially shows a patterned image before revealing the actual content. This method creates visually appealing content while waiting for the entire webpage to load. Upon inspecting ...

Execute a function every 10 seconds after it finishes running (JavaScript)

I am currently facing a challenge with a function that utilizes the "post" method to retrieve data from the server for processing. The amount of data retrieved varies, leading to longer completion times (around 30 seconds). My goal is to have this functi ...

Having trouble choosing multiple options from autocomplete drop-down with Selenium web-driver in Python

I am currently in the process of automating a webpage built with Angular that features an auto-complete dropdown with numerous elements. My goal is to click on each individual element and verify if it populates all the fields below accordingly. Below is th ...

Can someone please explain the distinction between $http.get() and axios.get() when used in vue.js?

I'm feeling a little bit puzzled trying to differentiate between $http.get() and axios.get(). I've searched through various sources but haven't found any answers that fully satisfy me. Can someone please offer some assistance? ...