Vue.js - encountering an issue with undefined response data

Greetings! I've encountered a script issue while trying to submit a form in VUE. The error message displayed in the developer panel states: "TypeError: error.response.data.errors is undefined". As a newcomer to Vue, I'm seeking some assistance as I can't seem to pinpoint the problem. Despite checking namespaces multiple times, the issue persists. It's perplexing why the data errors are showing up as undefined.

Store controller:

public function store(Request $request)
    {
      $this->validate($request, [
        'flight_no'        => 'required|max:255',
        'fromICAO' => 'required',
    ]);

    $roster = Roster::create([
        'flight_no'=> request('flight_no'),
        'fromICAO' => request('fromICAO')

    ]);

    return response()->json([
        'roster'    => $roster,
        'message' => 'Success'
    ], 200);
    }

Roster.vue

<template>
    <div class="container">
        <div class="row">
            <div class="col-md-12 " style="margin-top:10px;">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <button @click="initAddRoster()" class="btn btn-primary btn-xs pull-right" style="background-color:#bdc911; border:none">
                            + Add New Route
                        </button>
                        Roster
                    </div>

                    <div class="panel-body">

                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" tabindex="-1" role="dialog" id="add_roster_model">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">Add New Route</h4>
                    </div>
                    <div class="modal-body">

                        <div class="alert alert-danger" v-if="errors.length > 0">
                            <ul>
                                <li v-for="error in errors">{{ error }}</li>
                            </ul>
                        </div>

                        <div class="form-group">
                            <label for="flight_no">Flight number:</label>
                            <input type="text" name="flight_no" id="flight_no" placeholder="Flight number" class="form-control"
                                   v-model="roster.flight_no">
                        </div>
                        <div class="form-group">
                            <label for="fromICAO">From ICAO:</label>
                            <textarea name="fromICAO" id="fromICAO" cols="30" rows="5" class="form-control"
                                      placeholder="from ICAO" v-model="roster.fromICAO"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" @click="createRoster" class="btn btn-primary">Submit</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->

    </div>
</template>

<script>
    export default {
        data(){
            return {
                roster: {
                    flight_no: '',
                    fromICAO: ''
                },
                errors: []
            }
        },
        methods: {
            initAddRoster()
            {
                this.errors = [];
                $("#add_roster_model").modal("show");
            },
            createRoster()
            {
                axios.post('/roster', {
                    flight_no: this.roster.flight_no,
                    fromICAO: this.roster.fromICAO,
                })
                    .then(response => {

                        this.reset();

                        $("#add_roster_model").modal("hide");

                    })
                    .catch(error => {
                        this.errors = [];
                        if (error.response.data.errors.flight_no) {
                            this.errors.push(error.response.data.errors.flight_no[0]);
                        }

                        if (error.response.data.errors.fromICAO) {
                            this.errors.push(error.response.data.errors.fromICAO[0]);
                        }
                    });
            },
            reset()
            {
                this.roster.flight_no = '';
                this.roster.fromICAO = '';
            },
        }
    }
</script>

Answer №1

404 error response indicates that the response does not have an error attribute, so it cannot be added to the if condition.

For debugging purposes in the future, you can utilize the console.

.catch(error => {
    this.errors = [];
    // Debugging can be done here
    console.log(error);
 });

Example:

// The following data will be received from the ajax call
var error = {
   data: {
     'error': 'some data we can see it in console'
   }   
}

console.log(error);

Answer №2

Solution:

The issue lied in the incorrect route path that was specified:

axios.post('/roster'

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

Modify the state from a listener that is enclosed in the useEffect function

Within my hook called useQueryEvents, I have a setup that involves fetching all past transactions for a user and listening to the network for incoming/outgoing transactions. These transactions are then passed into a function called addActionToActivity, whi ...

Issues with React router arise once the app has been built

I am new to utilizing react and react-router in my project. I have built the application using create-react-app and now I am facing an issue with routing between two main pages. After trying different approaches, I managed to get it working during develop ...

What is the best way to merge two JSON arrays using Axios in a React project?

I am currently working on getting data using axios React from Laravel, but I am facing some challenges in combining two arrays by their respective Ids. In my case, I am trying to retrieve product data and images from the Laravel Controller. Can anyone prov ...

Working with npm objects across multiple files

My goal is to integrate the npm package for parallax (lax.js) into my project. The documentation states that in order to initialize it, the following code snippet should be included: window.onload = function () { lax.init() // Add a driver that we use ...

What methods can be used to ensure a required minimum delay time between function executions?

For my node function, I am aiming for a specific execution delay of around 5 seconds. The minimum delay needs to be implemented within the function itself, not externally, so external users are unaware of the delay. Therefore, I cannot rely on modules l ...

Is it possible to create a personalized serialize form when sending an AJAX POST request

How can I format form data on an AJAX POST request differently than the default $("#formid").serialze()? The current result is not suitable for my needs, as it looks like this: `poststring="csrfmiddlewaretoken=bb9SOkN756QSgTbdJYDTvIz7KYtAdZ4A&colname= ...

Capturing the returned value of a mutation in another mutation in Vuex

Having trouble accessing a getter from an action, and receiving the error message: getters.isCardLiked is not a function store/index.js export const getters = { isCardLiked(state, id) { const found = state.likedCards.find(likedCard => liked ...

Using Angular JS, the JSON method is invoked from a location external to the controller

How can I call an inner method from outside a controller in AngularJS? var app; (function (){ app = angular.module("gallery", []); app.controller("galleryController", ['$scope','$http', function($scope, $http){ var gallery = this; ...

Is there a way I can set a variable as global in a jade template?

I am trying to pass a global object to a jade template so that I can use it for various purposes later on. For instance: app.get("/", function(req, res){ var options = { myGlobal : {// This is the object I want to be global "prop ...

Checking the validity of a username through regex

I have implemented a Username field validation in Vue using regex. A key down event triggers the method below with each keystroke: userNameValidation(event) { if (!event.key.match(/^[a-zA-Z0-9._]+$/)) { event.preventDefault(); } ...

Three divs are set in place, with two of them of fixed width while the third div is

Looking for a layout with specific positioning and fixed widths: One box on the left, one box on the right, each with a width of 200px. The middle div should adjust to take up the remaining space. Any suggestions are appreciated. Thank you! ...

What sets apart toBeInTheDocument from getBy* in @testing-library/react?

Can you distinguish between these two methods in react-testing-library? expect(screen.queryByText('<something>')).toBeInTheDocument(); And screen.getByText('<something>'); (The specific getBy* and queryBy* operation are no ...

Error: The socket.io client script cannot be found when using Express + socket.io

This situation is really getting to me... even though I have a functioning version of Express + Socket.io, I can't replicate it in a new project folder with standard NPM installs. Can someone please help me figure out what I'm doing wrong...? Her ...

Exploring ways to run tests on a server REST API using testem

When using Testem, I have a config option called serve_files that handles serving the client-side code for me. However, I also need to run my server because it includes a REST API that the client side relies on. Is there a way to configure Testem to launc ...

Unravel the mystery of decrypting tokens in Vue.js!

I received a token upon successful login, and now I need to decode or decrypt it in order to view the permissions information contained within. How can I achieve this? I attempted: // token is accessible var decoded = jwt_decode(token) console.log(' ...

Retrieving visual information from Google Street View entity

Looking for a solution to extract imagery from the Google Street View panorama within a web page? In my program, I navigate specific routes using Google Street View's javascript API controlled by an embedded Java applet on the same page. I am seeking ...

What is the most efficient way to calculate the current percentage of time that has elapsed today

Is there a way to calculate the current time elapsed percentage of today's time using either JavaScript or PHP? Any tips on how to achieve this? ...

Swap out The div element with the html() method

I'm encountering an issue when trying to swap out a div element with ajax. My goal is to create a start/stop button functionality. The page displays a list of card elements, each with its own button, which are stored in separate html files. work_orde ...

What is the true appearance of Ajax?

After spending a few days researching Ajax to use with the Django Python framework, I came across numerous resources on the topic. 1. function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyStat ...

Unexpected output from nested loop implementation

Having some arrays, I am now trying to iterate through all tab names and exclude the values present in the exclusion list. json1 ={ "sku Brand": "abc", "strngth": "ALL", "area ...