The authentication error display feature is not functioning as intended in the Vue login component due to a problem

I am currently learning Laravel and Vue through an online course on Udemy. In order to test if the push function works within a Vue component, I am trying to display a failed authentication error response for a 422 error (this is just for testing purposes and the code will be refactored later).

Despite conducting some research, I have not found any solutions yet.

<template>


 <div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
      <div class="card card-shadowed p-50 w-400 mb-0" style="max-width: 100%">
          <h5 class="text-uppercase text-center">Login</h5>
          <br><br>
    <form>
      <ul class="list-group alert alert-danger" v-if="errors.length > 0">
        <li class="list-group-item" v-for="error in errors" :key="errors.indexOf(error)">
           {{ error }}
        </li>
            </ul>
            <div class="form-group">
              <input type="text" class="form-control" placeholder="Email" v-model="email">
            </div>
    
            <div class="form-group">
              <input type="password" class="form-control" placeholder="Password" v-model="password">
            </div>
    
            <div class="form-group flexbox py-10">
              <label class="custom-control custom-checkbox">
                <input type="checkbox" class="custom-control-input"  v-model="remember" checked>
                <span class="custom-control-indicator"></span>
                <span class="custom-control-description">Remember me</span>
              </label>
    
              <a class="text-muted hover-primary fs-13" href="#">Forgot password?</a>
            </div>
    
            <div class="form-group">
              <button class="btn btn-bold btn-block btn-primary" @click="attemptLogin()" :disabled="!isValidLoginForm()" type="button">Login</button>
            </div>
          </form>
          <p class="text-center text-muted fs-13 mt-20">Don't have an account? <a href="page-register.html">Sign up</a></p>
        </div>
      </div>
    </div>
    </template>
    
    <script>
        import axios from 'axios';
        import qs from 'qs';
        export default {
            mounted() {
                console.log('Component mounted.')
            },
            data() {
              return {
                email: '',
                password: '',
                remember: true,
                loading: false,
                errors: [],
              }
            },
            methods: {
              emailIsValid() {
               if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(this.email)) {
                  return true
                } else {
                  return false
                }
              },
    
              isValidLoginForm() {
                return this.emailIsValid() && this.password && !this.loading
              },
    
              attemptLogin() {
          

      var the_data = {
                  email: this.email,
                  password: this.password,
                  remember: this.remember,
                }
                this.errors = [];
                this.loading = true;
                axios.post('/login', the_data)
                .then(function (response) {
                  location.reload();
                })
                .catch(function (error) {
                  this.loading = false;
                  if (error.response.status == 422) {
                    this.errors.push("We couldn't verify your account details.");
                  } else {
                    this.errors.push("Something went wrong, please refresh and try again.");
                  }
                });
              }
            },
    
            // computed: {
            //
            // },
        }
    </script>

Although I do not receive any errors when entering wrong user credentials in the view, the console shows a 422 error response. I am trying to display a readable response in the alert, such as "We couldn't verify your account details", but I have not been successful so far.

Answer №1

Following the advice from @Noogen to remove qs.stringify, I encountered an unexpected solution by altering the structure of the 'then and catch blocks' which resolved the issue (resulting in a 422 console error and appropriately pushing the error to the component): `

 attemptLogin() {
    var the_data = {
      email: this.email,
      password: this.password,
      remember: this.remember,
    }
    this.errors = [];
    this.loading = true;
    axios.post('/login', the_data)
    .then(response => {
      location.reload();
    })
    .catch(error => {
      this.loading = false;
        console.log(error.response)
        if (error.response.status == 422) {
           this.errors.push("We couldn't verify your account details.");
         } else {
           this.errors.push("Something went wrong, please refresh and try again.");
         }
    });
  }
},`

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

I am having trouble getting the bootstrap link and css files to work on a specific URL. Can you please help me troubleshoot this issue and let me know if there are any additional files needed to

When attempting to apply the bootstrap link and css files to the URL "/list/:customListName", they are not working. However, changing the URL to "/:customListName" somehow makes it work. What is the reason behind this behavior and how can I properly style ...

Switch up div containers with JavaScript based on the set array order of elements?

As I work on creating a list that calculates the sum of selected numbers, I encountered an issue with rearranging the items. Despite successful functionalities like adding images with names, changing languages, and performing calculations, the page keeps r ...

The background image and svgs are not displayed on laravel localhost/public/index.php, but they appear when using "php artisan serve"

I've created a beautiful Laravel project on my PC. The welcome.blade.php file in the project has a background image located in the: public/images/ directory. To display the images, I've used the following CSS: html, body { color: #f4f6f7; ...

Protractor tests are successful when run locally, but encounter failures when executed on Travis-CI

I recently integrated end-to-end tests using Protractor into my AngularJS application. Testing them locally showed that they all pass, but upon committing to GitHub and Travis for CI, most of the tests fail. The failing tests seem to be those requiring na ...

Unexpected Disconnection of AJAX Response Moments Before Rebooting the Raspberry Pi

I currently have a LAMP server set up on my Raspberry Pi 4, where a web page is utilizing an AJAX call to trigger a php script that initiates a reboot of the pi. The php script echoes a JSON string response back to the web page indicating that it is prepar ...

AJAX request encounters error when trying to send file, receiving a 'blob' error message

I've been struggling with an AJAX request that is supposed to send a file to my controller, where it should be read and then a sorted array returned to the front-end. Unfortunately, I keep getting stuck on an error related to a 'blob' not be ...

Construct a new array within a JavaScript constructor function

I have been working on setting up a constructor and trying to initialize an array inside the object that will be created. This specific array is meant to hold multiple objects. function Cluster3DObject(name){ this.name = name; ...

My global variable keeps getting caught by the addEventListener function

My script does not use jQuery and has an addEventListener on a button click. The issue is that after the first run, I want to change the value of "sendingurl" to something else. However, even though sendingurl is updated with the new id value, it doesn&apo ...

Elevating the Material Design Lite Progress bar using ReactJS

I currently have MDL running with React and it appears to be functioning properly. The Progress Bar is displaying on the page as expected, loading with the specified progress on page load when a number is entered directly: document.querySelector('#qu ...

Whenever I try to open my jQuery UI Dialog without first displaying an alert, it does not work

Beginning of my HTML page, initializing a dialog : <script type="text/javascript"> $(function() { $( "#dialog-confirm" ).dialog({ autoOpen: false, resizable: true, height:180, width:300, modal: true, buttons: { "Yes": ...

Utilizing the Angular *ngFor directive to iterate through JSON data

Just stepping into the world of Angular, I want to share a brief overview of my goal since the code is lengthy. Here's the relevant part: Within my project, I have a list display component. And I have two components, namely animals and zone. For in ...

How can you automate the execution of unit tests in Angular before pushing changes to Git?

There have been instances in Angular projects where the unit tests are triggered every time a build is carried out, as well as when running the git push command. In case any tests fail during either of these commands, the process halts until all unit tes ...

"Turn a blind eye to Restangular's setRequestInterceptor just this

When setting up my application, I utilize Restangular.setRequestInterceptor() to trigger a function that displays a loading screen whenever a request is made with Restangular. Yet, there is a specific section in my application where I do not want this fun ...

Using HTML and CSS to create a Contact Form

Greetings! I have come across this contact form code: /* Custom Contact Form Styling */ input[type=text], [type=email], select, textarea { width: 100%; padding: 12px; border: 1px solid #555; margin-top: 6px; margin-bottom: 16px; resize: v ...

How can I stop a browser from refreshing when I click the mouse?

After taking steps to prevent the browser back button from functioning by clearing history and disabling key events for page refresh, I am now seeking a way to also stop mouse clicks on the browser's refresh button. Can anyone offer assistance with th ...

I'm struggling to figure out the best method for updating data properties in Vue. Computed properties and watchers aren't getting the job done. What

I'm facing a challenge with updating certain input fields on a form I'm currently working on. After receiving data from axios in one data property, I am attempting to prefill some fields with the response. There are four fields returned from the ...

Use two queries to apply filters to entries in NextJS

Greetings to all! I am currently working on a project in NextJS that involves showcasing a portfolio of works generated from JSON data. [ { "title": "WordPress Plugin for Yandex Recommender Widget", "image" ...

Perform multiple function invocations on a single variable using JavaScript

Is there a way to execute multiple functions on a single object in JavaScript? Maybe something like this: element .setHtml('test'), .setColor('green'); Instead of: element.setHtml('test'); element.setColor('gre ...

The JavaScript array slideshow is experiencing some glitches in its transition

After diving into JavaScript recently, I managed to center a div and make it fullscreen as the window resizes. However, things got tricky when I added a script I found online to create an image transition using an array. Unfortunately, these scripts are co ...

Struggling to securely post data to an Express server by hashing passwords with bcrypt?

I'm currently working on developing an API using Express and Sequelize. Specifically, I am writing a function to create a new user where I utilize bcrypt for password hashing. const createNewUser = (data) => { return new Promise(async (resolve, ...