Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Axios Failed with status code 419 using Vue

Concept: I have an application that allows users post a question... When the user clicks the Ask button i trying to submit the the quesiton using Vue.js and Axios.

Problem: 70% of the time the question is submitted properly, but 30% of the time it fails and returns "Failed to load resource: the server responded with a status of 419 (unknown status)"

enter image description here

My Vue component

<template>
    <div id = "main_question_box" class = "tab-pane fade">
        <div class="panel-body posting-field-box">        
            <textarea name="feed_body" class="summernote posting-field form-control"></textarea>
            <button class = "example-btn btn btn-xs btn-default pull-right">View Question Examples</button>                                    
        </div>

        <div class="panel-footer">
            <ul class="list-inline pull-right">
                <li>
                    <button @click = "sendPost" class="feed-post-btn btn btn-submit btn-sm btn-success pl-l pr-l">
                        <span>Ask</span>
                        <i class="fa fa-paper-plane pl-sm"></i>
                    </button>
                </li>
            </ul>

            <div class="clearfix"></div>
        </div>
    </div>
</template>

<script>

    axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content')

    export default {
        props:['timelineId'],
        data(){
            return {
                feed_body: '',
                timeline_id: this.timelineId,
                type: 'Question',
                post_ready: false
            } 
        }, 
        methods: {
            sendPost: function () {
                this.compilePost(this);
                if(this.post_ready){
                    var self = this;
                    self.startLoader();
                    axios.post('/timeline',
                    {
                        feed_body: this.feed_body,
                        timeline_id: this.timeline_id,
                        feed_type: this.type

                    }).then(response =>{
                        this.feed_body = '';
                        this.post_ready = false;
                        $('#main_question_box .summernote').summernote('code', '');
                        this.$emit('newFeedSent', response.data);
                    });
                }
            },
            startLoader: function(){
                $('.feed-post-btn').addClass('btn-default').removeClass('btn-success').prop('disabled', true).find('span').hide();
                $('.feed-post-btn').find('i').attr('class', 'fa fa-cog fa-spin fa-2x fa-fw');       
            },
            compilePost: function(instance) {
                var editor = $('#main_question_box .summernote');
                var isEmpty = $(editor).summernote('isEmpty');
                if(!isEmpty){
                    instance.feed_body = $(editor).summernote('code');
                    instance.post_ready = true;
                }else{
                    instance.post_ready = false;
                }
            }
        }
    }

</script>

My Web.php

Route::post('/timeline', 'FeedController@storeFeed');

My Controller

public function storeFeed(Request $request)
{

    if($request->feed_type == 'Debate'){
        $this->validate(request(), [
            'feed_subject' => 'required',
            'feed_body' => 'required',
        ]);

        $publishedFeed = Auth::user()->publishDebate($request);

    }elseif($request->feed_type == 'Question'){
        $this->validate(request(), [
            'feed_body' => 'required',
        ]);

        $publishedFeed = Auth::user()->publishQuestion($request);

    }else{
        $this->validate(request(), [
            'feed_body' => 'required',
        ]);

        $publishedFeed = Auth::user()->publishPost($request);
    }


    return $publishedFeed->id;

}

My HTML Head

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="login-status" content="{{ Auth::check() }}">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

My resources\assets\js\Bootstrap.js

    window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
like image 428
Julian Tabona Avatar asked Nov 20 '17 12:11

Julian Tabona


People also ask

How to fix the code 419 error in Laravel?

The 419 code corresponds to the absence of the csrf token . To tackle this issue, simply put this into your head: And pass it with every request you make to Laravel.

How to send Form data to controller using Axios POST request in Laravel?

The above code is to send form data to controller using axios post request in laravel. Next, Go to resources/assets/js then open app.js file and intialize vue js components in this file. So open app.js file and update the following code into your app.js file: Now, Open resources/layouts/app.blade.php and update the following code into it:

What to do when request status code 419 fails?

As a response to the request I get: Request failed with status code 419 If it is a post request.... send also _token as an input/request data. It cannot hurt to try. Show activity on this post.

What about 422 Unprocessable Entity in Laravel?

What about 422 Unprocessable Entity ? This error occurs when your backend validation fails. If you let Laravel refresh your page after POST request, you get errors in @errors directive and stuff, but usually, you want to handle it via ajax either because you care about user experience, or you use a frontend framework such as React or Vue.


1 Answers

I can reproduce this problem.

  1. Use Vuejs/Laravel app as normal.
  2. Refresh page with \Session::flush() in your controller public function getProduct(Request $request) { \Session::flush(); return view('product'); }

  3. Make a put/post request from client ->Request failed with status code 419

  4. This likely means that in development your session expires so you can try to set your session lifetime to a higher number to see if that resolves the issue.
like image 85
egekhter Avatar answered Sep 30 '22 21:09

egekhter