Axios - Show the error message returned from validation as [object Object]

Within my API, I include the following validation logic:

$request->validate([
        'firstname' => 'required',
        'lastname' => 'required',
        'username' => 'required|unique:users',
        'email' => 'required|email|unique:users',
        'password' => 'required'
    ]);

Following that, I handle errors in Axios with the following code:

.catch(error=>{
    console.log("Error: " + error.response.data.errors)
})

However, this results in displaying: Error: [object Object]

If I intentionally provide a username that already exists in the database, and then modify the catch block to

.catch(error=>{
    console.log("Error: " + error.response.data.errors.username)
})

The output will be Username is already taken which is desirable.

This poses the challenge of having to explicitly specify

error.response.data.errors.<x error>
to display the message. For instance, if I use data.errors.username but the email triggers the validation error, the console will show Error: undefined as there is no data.errors.username, only data.errors.email.

Is there a way to access and present the returned error without manual specification? Your assistance is greatly appreciated!

Answer №1

To display the error object values, you can access them by using the Object.values(errors) method to retrieve arrays of values. Then, utilize the flat() function to combine these arrays into one single array. Lastly, concatenate the values together using the join() method like so:

  console.log(Object.values(error.response.data.errors).flat().join())

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

Having trouble deciphering this snippet of Express JS source code

Upon reviewing the Express JS source code, I came across the main module where express is being exported. module.exports = createApplication; function createApplication() { var app = function(req, res, next) { app.handle(req, res, next); }; m ...

In a Vue application, how can the API path be determined during the build by utilizing environment variables?

I am looking for a way to dynamically change the 'root path' of my site's API in a Vue application. I want the API path to be determined during the build process based on a variable value. This feature is available in Angular, but I'm n ...

What strategies can be used to effectively manage multiple asynchronous requests?

I have two requirements: one is to load an image (which will take a long time on the backend server), and the other is to perform an AJAX request. I would like it to be structured like this: $.when( [perform image loading] [perform ajax request] ).t ...

displaying data once "other" is chosen from a dynamic chart

I am having an issue with a dynamic table where I have a dropdown list with the option "other", and I want to display additional input when "other" is selected. Currently, the function I have only hides the input that is always visible and does not show ...

Exploring X3DOM nodes using d3.js

I'm attempting to loop through X3DOM nodes in D3.js, but I'm encountering an issue. Check out the code snippet below: var disktransform = scene.selectAll('.disktransform'); var shape = disktransform .datum(slices ...

What are some ways to include additional data besides the new value in a change event for an input field?

Currently, I am using VueJS to dynamically generate a form based on a JSON schema and then attempting to save the data into my Vuex state. Here is an overview of the code I have written so far (simplified): <div v-for="field in schema" :key=& ...

Images are failing to render on Next.js

Hello there! I am facing an issue while working on my Next.js + TypeScript application. I need to ensure that all the images in the array passed through props are displayed. My initial approach was to pass the path and retrieve the image directly from the ...

Adding external JavaScript files that rely on jQuery to a ReactJS project

As a beginner in web development, I have a question regarding importing external JavaScript files in ReactJS. I currently have the following imports: import $ from 'jquery'; window.jQuery = $; window.$ = $; global.jQuery = $; import './asse ...

Refresh the Data Displayed Based on the Information Received from the API

As someone who is relatively new to React, I have been making progress with my small app that utilizes React on the frontend and a .NET Core API on the server-side to provide data. However, I have encountered a problem that I've been grappling with fo ...

Issue: NextRouter is not mounted when the client is used

After implementing use client, I encountered the following error: Error: NextRouter was not mounted error. However, upon removing use client, a different error surfaced: Error when use client is removed: ReactServerComponentsError: A component requirin ...

How can we manually trigger $(document).ready() from within the ready callback of head.js using jQuery?

I am in search of ways to enhance the loading speed of a web application, particularly one that encompasses numerous javascript files on every HTML page. My plan is to experiment with head.js on a specific page to observe if it has a positive impact on loa ...

Encountered an issue while attempting to make a GET request using the fetch API

Currently, I am attempting to retrieve some data from the server using react.js and the fetch API. However, I keep encountering this error: SyntaxError: Unexpected token < in JSON at position 0. This is the code snippet I am using to fetch the data: ...

Is there a way for me to execute a function multiple times in a continuous manner?

I am attempting to create a blinking box by calling a function within itself. The function I have is as follows: $(document).ready(function(){ $("button").click(function(){ $("#div1").fadeToggle("slow"); }); }); <script src="https://a ...

Is there a way to automatically adjust the positioning of added pins on an image as I scroll through the image?

I have inserted a large image onto my HTML page and to manage its size, I am displaying it within a div that allows for scrolling like a map. Using jQuery, I have placed 3 markers on the image. The issue I am facing is that when I scroll the image, the ma ...

Encountering a "Duplicate identifier error" when transitioning TypeScript code to JavaScript

I'm currently using VSCode for working with TypeScript, and I've encountered an issue while compiling to JavaScript. The problem arises when the IDE notifies me that certain elements - like classes or variables - are duplicates. This duplication ...

The impact of React-router's history within the connect function of the react-redux provider

After successfully connecting my presentational-functional component to the redux store using the connect function, I encountered an issue regarding redirection upon triggering the getTask action or when apiGetTask has completed. I attempted to implement t ...

Troubleshooting: Success with AJAX call in Chrome, but issues in IE

Having issues retrieving JSON data from a URL that displays the last 3 numbers of a webpage. The AJAX call functions correctly in Google Chrome but fails in Internet Explorer. I tried disabling caching using cache: false as suggested, but the problem persi ...

Dealing with Axios cross-origin resource sharing problem in communication between VueJS frontend and SailsJS backend

I've tried everything to solve this issue but I'm still struggling to establish an Axios connection between my VueJs frontend and SailsJS backend. My Vue app is running on localhost:8080, while Sails is running on localhost:1337. Here is the erro ...

what is the most effective method for integrating Vue with Express?

1: I have successfully installed expressjs on my system. 2: Following that, I used npm to install the vue framework by running 'npm install vue --save'. 3: Additionally, I utilized handlebars as the template-engine for expressjs. In my index.hbs ...

The product has been taken out of the cart, yet it has not been reinserted into the cart

The product disappears from the cart after clicking on Add to Cart, but it doesn't reappear when clicked again. //function for adding only one item to cart document.getElementById('btn1').onclick = function() { addItemToCart() }; fun ...