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

ES6 does not support two-way binding functionality

Let's take a look at this snippet of code: export class TestController { constructor() { this.socket = io(); this.movies = {}; this.socket.emit('getAllMovies', ''); this.socket.on('allMovi ...

Discovering and sorting an array in Vue.js based on IDs

Hello everyone, I've been attempting to filter my results using the filter and includes methods but it doesn't seem to be working. Does anyone have a solution for this, perhaps involving includes or something similar? companies ids [1,2,3] user c ...

Module exists; however, command could not be located

I am experiencing an issue with the rimraf node module. Despite being able to access its folder within the node_modules directory, I am receiving errors indicating that the command for rimraf cannot be found. I have attempted to delete the entire node_mod ...

The Jest mock for dates is completely ineffective and always ends up returning the constructor

beforeAll(() => { ... const mockedData = '2020-11-26T00:00:00.000Z' jest.spyOn(global, 'Date').mockImplementation(() => mockedData) Date.now = () => 1606348800 }) describe('getIventory', () => { ...

Creating unit tests for linked functions in Node.js using Jest

Hey there! I'm looking to test a function using Jest that involves token verification and requires 3 parameters. Here's the code for the function: const verifyToken = (req, res, next) => { // Checking for token in header or URL parameter ...

When the margin-left changes, SVG begins to flicker and shake in a marquee effect

I've been experimenting with a marquee effect using vanilla JS. The effect is working, but I'm encountering some shaking issues with SVG and images as they move. <div class="marquee"> <h1>Nepal <svg version="1.1&qu ...

Expanding a class functionality by incorporating a method through .prototype

My goal is to define a class called "User" and then add a method to the class using the "prototype" keyword. I want the method "who_auto" to be accessible to all future instances of "User". When testing this code in JSFiddle, I encountered the error messa ...

Using Javascript, dynamically animate the text in the hero unit with fading in and out effects

I currently have a "Hero" unit with the following code: <div class="hero-unit"> <div class="container"> <h1>Dapibus Euismod Mollis</h1> <p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis ...

Tips for enhancing the appearance of a React component

I have a redux form that doesn't look great, and I would like to style it. However, my project uses modular CSS loaders. The styling currently looks like this: import styled from 'styled-components'; const Input = styled.input` color: #4 ...

Avoiding the occurrence of moiré patterns when using pixi.js

My goal is to create a zoomable canvas with rectangles arranged in a grid using pixi.js. Despite everything working smoothly, I'm facing heavy moire effects due to the grid. My understanding of pixi.js and webgl is limited, but I suspect that the anti ...

Navigating with React Router v6 beyond the confines of individual components

When using react-router v5, I would create the history object like this: import { createBrowserHistory } from "history"; export const history = createBrowserHistory(); Then I would pass it to the Router like so: import { Router, Switch, Route, Link } from ...

What are the steps to transform an object containing arrays into strings and then embed them into my HTML code?

Here is the code I need to add to my errors array and send the values to my HTML client-side template: { "email": [ "user with this email already exists." ] } I am looking for something like this: "user with t ...

Locate a specific text within a complex array of objects and retrieve the objects that contain the match as

I have an array of objects named input as shown below. Each object in the array contains a property vertical of type string, an array called platformList, and a nested object named radar_metadata. I am looking to implement a search functionality where I c ...

What is the best way to convert a string to an integer in JavaScript while still maintaining compatibility with Internet Explorer 11?

Here is the code snippet that I am working with: setCol (param) { // missing forEach on NodeList for IE11 if (window.NodeList && !NodeList.prototype.forEach) { NodeList.prototype.forEach = Array.prototype.forEach; } const a ...

What is the best way to create a clickable <li> element from AJAX search results that display dynamic HTML?

Utilizing AJAX technology, I have implemented a live search feature that populates results from a database as the user types in a text field. The results are presented in an unordered list format. My goal is to allow users to click on an item within the li ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Using Vuex as a global event bus ensures that all subscribers will always receive notifications for

For a while now, I have relied on a global event bus in Vue - creating it as const bus = new Vue(). It works well, but managing subscriptions can get tedious at times. Imagine subscribing to an event in a component: mounted() { bus.$on('some.event ...

An alternative approach to coding

I am a JavaScript developer who writes code to handle multiple keys being pressed simultaneously. The current implementation involves checking each key's keyCode individually, which I find cumbersome. var key = event.keyCode; if (key === 39 { / ...

How to style text in CSS with a numbered underline beneath

Is there a way to apply underlining to text and include a small number underneath the underline in a similar style shown in this image, by utilizing css, html, or javascript? ...

Adjustable dimensions for a collection of squares based on screen size

I am currently designing a grid composed of 1:1 squares and allowing the user to continually add more squares. My main goal is to ensure that the size of each square maintains its aspect ratio while being able to resize accordingly. The challenge lies in k ...