Laravel Axios Failed with status code 419 using Vue
Asked Answered
P

1

7

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');
}
Practicable answered 20/11, 2017 at 12:17 Comment(4)
It probably isn't a 419 error but the 500 error you are getting before your 419. Click on your network tab and post the 500 error. The unknown status is because of the 500 error.Mechellemechlin
In case the root problem actually is the 419 and not the 500 before that, as @Mechellemechlin suggested: Laravel throwing 419s mostly comes from csrf token problems and api routes. See if this question, this question or this forum post can be of any use to you.Quinonez
can you post what the network panel in chrome console says?Greensboro
I don't see how you route '/timeline' is protected since you don't use any auth middleware in the shown codeZenithal
T
2

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.
Tabulate answered 1/6, 2019 at 15:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.