post request using axios on Laravel 5.5

拟墨画扇 提交于 2019-12-07 06:44:48

问题


i'm trying to make some requests using axios and the last Laravel version 5.5 after configure the X-CSRF fields and all my code is simple :

        axios.post('/post-contact',{name:'Kamal Abounaim'})
        .then((response)=>{
            console.log(response)
        }).catch((error)=>{
            console.log(error.response.data)
        })

but i get this error : 419 (unknown status) what the problem supposed to be Thanks for answering


回答1:


This is happening because of the csrf-token. Just add meta tag with the csrf-token in the <head> and add that token to axios header like so.

// in the <head>
<meta name="csrf-token" content="{{ csrf_token() }}">

<script type="text/javascript">
    // For adding the token to axios header (add this only one time).
    var token = document.head.querySelector('meta[name="csrf-token"]');
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;

    // send contact form data.
    axios.post('/post-contact',{name:'Kamal Abounaim'
    }).then((response)=>{
        console.log(response)
    }).catch((error)=>{
        console.log(error.response.data)
    });
</script>



回答2:


A 419 error seems to be Authentification Timeout. Your code looks fine to me, so it seems the error is with the post-contact endpoint? Try testing that endpoint alone, in a tool like postman.




回答3:


It is VerifyCsrfToken middleware... Just comment it in app/Http/Kernel.php

protected $middlewareGroups = [
        'web' => [
            .. middlewares before
            //\App\Http\Middleware\VerifyCsrfToken::class, -> comment this or delete
            .. other
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

I have same problem and thanks to @abdalla arbab :)



来源:https://stackoverflow.com/questions/46084980/post-request-using-axios-on-laravel-5-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!