Displaying API errors using JavaScript

As a novice web developer, I recently completed my first project using Vue and Laravel 8.

However, when trying to access my API, I encountered an error message: {"message":"The given data was invalid.","errors":{"email":["This email already exists."],"login":["This login is already taken."]}}

I have included the following code:

axios.post(this.$apiAdress + '/api/administrators?token=' + localStorage.getItem("api_token"),
        self.record
      )
        .then(function (response) {
          if (response.data.status == 'success') {
            Swal.fire(
              'Success',
              'Record added successfully!',
              'success'
            )
          } else {
            Swal.fire(
              'Error',
              response,
              'error'
            )
          }
          this.$router.replace({path: '/administrators/create'});
        }).catch(function (error) {
        if (error.response.data.message == 'The given data was invalid.') {
          Swal.fire(
            'Error',
            'Please fill in all required fields!',
            'error'
          )
          window.scrollTo({top: 0});
        }

The line: error.response.data.message indicates the presence of errors.

My goal is to display these errors using Swal:

Swal.fire(
                'Error',
                '.... Here goes the list of errors ....',
                'error'
              )

For instance:

Swal.fire(
                    'Error',
                    'This email already exists. <br/> This login is already taken.',
                    'error'
                  )

How can I achieve this?

Your assistance would be greatly appreciated.

Answer №1

To handle errors, you can simply loop through the errors object like this:

if (error.response.data.message == 'The given data was invalid.') {
    let error_details = ""

    for (let key in error.response.data.errors) {
        error_details += `${error.response.data.errors[key]}<br/>`
    }

    Swal.fire(
        'Error',
         error_details,
        'error'
    )
    // ...
}

Answer №2

Here's a solution that should be effective in the given scenario:

Swal.fire(
  'Error',
  error.response.data.email + "<br />" + error.response.data.login,
  'error'
)

Answer №3

Instead of printing the entire object, you should access specific properties:

"[object Object]"

To retrieve a property from the object:

response.error.email
// The email already exists. <br/> The login already exists.

If you want to print the object as a string:

JSON.stringify(response);

You can also extract specific errors:

var errors = JSON.parse('{"message":"' + response.message + '","errors":' + JSON.stringify(response.errors) + '}');
// Object { ... }

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 causes images to be omitted from a PDF file when using mywindow.print()?

Here is the scenario I am dealing with: On a particular webpage, there is a print button. The page contains various information, including receipts. When the user clicks on "print", I want only the receipts to be printed: https://i.sstatic.net/WobKK.png ...

Extract the content from the division and set it as the image source

Looking for a way to retrieve the content from a div and insert that into the 'src' parameter of an image. Working on a project where JSON is used to load translation files, preventing me from loading images directly, but I want to at least load ...

Verifying authentication on the server and redirecting if not authorized

I am working on my NEXTJS project and I want to implement a feature where the cookie headers (httponly) are checked and the JWT is validated server-side. In case the user is not logged in, I would like to respond with a 302 redirect to /login. I'm unc ...

Sophisticated method for implementing dynamic components with props in Vue

In a specific scenario, I am using an API to output all the content for my Page, including its structure. To provide context, imagine a CMS with a page builder feature where authors can place components via drag and drop to create pages, which are then del ...

Formatting code within an HTML document

I am attempting to customize a stock widget that I obtained from financialcontent.com. My current approach involves using Bootstrap for styling purposes. To incorporate the widget into a div, I found it necessary to embed the script directly within the HT ...

Change the text field's border color if the field is not empty

On my website, there is a TextField where users can enter values to perform a site search. My question pertains to the border color of this field. Normally, the border color is black when the field is not in use. However, when a user clicks on the field an ...

Switching ng-Idle countdown time from seconds to minutes is possible by adjusting the configuration settings

I have implemented ng-idle in my application, where the warning popup appears after 10 seconds with the message: "Your session will be close in 10 seconds" However, I need to change this to minutes. The session should be closed in 5 minutes instead. How ...

What is the best way to access a variable's value from outside a promise?

I encountered an issue while trying to assign a value to a variable outside of a promise. Despite defining the variable outside the promise, it is showing up as undefined when I check its value. Could someone assist me with this problem by reviewing my co ...

What is the correct way to properly enter a Svelte component instance variable?

Currently, I am delving into learning Svelte and specifically exploring how to bind to a component instance as demonstrated in this tutorial: As I progress through the tutorial, I am attempting to convert it to Typescript. However, I have encountered an ...

Calling components may result in a race condition

I have integrated 2 components into my "App" that work together seamlessly. The first component is responsible for resolving the external IP address to a geographical location by making 2 axios.get calls and then passing them back to App.vue using emit. F ...

What is the best way to incorporate custom KnockoutJS functions using RequireJS?

I am facing an issue with my View Model that utilizes a custom observableArray function for sorting. The error message I receive states: "...has no methods 'sortByProperty'". How do I go about loading the handlers.js file to resolve this problem ...

Deactivating attribute inheritance / configuring component settings with script setup and Typescript

Is there a way to disable attribute inheritance for a component's options when using script setup syntax with Typescript in Vue 3? Here is the JavaScript code example: app.component('date-picker', { inheritAttrs: false, // [..] }) How ...

Is there a Vuetify component for inputting days, hours, and minutes using v-text-field?

Is it possible to format a v-text-field to allow selection of days, hours, and minutes instead of just hours and minutes? I have been reviewing the Vuetify documentation for text-fields and came across this solution: https://vuetifyjs.com/en/components/te ...

How to Ensure a Component is Loaded Only Once in React JS

Currently, I am working on a React App with two pages - Home and My Portfolio Section. The Portfolio Section consists of two functional components. Home.js import React from 'react' const Home = () => { return ( <h1>Home Screen&l ...

how can I enable pass-through functionality in express middleware?

Currently, I have a POST API endpoint named /users which is used to retrieve the list of users. The reason behind using POST instead of GET is because the request body can be quite large and it may not fit in the URL for a GET request. In this scenario, i ...

NodeJS API Language Configuration

I'm currently working on integrating the DuckDuckGo Instant Answer Api into my NodeJS application. To do so, I am making a data request from the API using Node Request. var request = require('request'); request('http://api.duckduckgo.c ...

What is the best way to showcase a QR code on a mesh using three.js?

I utilized the QRcode library available at to try and showcase it on a mesh object as a texture using the following code: var qrcode = new QRCode( "test", { text: "http://jindo.dev.naver.com/collie", width: 128, height: 128, colorDark : " ...

Obtain a fresh SQL identifier post submission through Ajax

When a comment is submitted on a post using ajax, the comment.php script will display the new comment with its own auto-incremented SQL id. It will look something like this: // The $id variable contains the SQL id after data submission <div class="comm ...

Tips for inserting the <style> element within a Vue.js component

Currently working with Vue.js v2, I am facing an issue where I have a CSS stylesheet stored as a string in a variable. import sitePackCss from '!!raw-loader!sass-loader!../../app/javascript/styles/site.sass'; I am trying to generate a <style& ...

Customize Cell Styling with Bootstrap Full Calendar CSS

I am attempting to implement a Bootstrap calendar feature where cells are colored green if the timestamp is greater than today's date. This can be achieved by: $checkTime > $today cell.css = green background I came across this code snippet on St ...