Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

post request using axios on Laravel 5.5

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

like image 951
Kamal L'azz Avatar asked Sep 06 '17 22:09

Kamal L'azz


People also ask

How do I send a POST request from Axios?

A POST request can be made using Axios to “post” data to an endpoint. This endpoint may then use this POST request to perform a certain task or trigger an event. The HTTP post request is performed by calling axios. post() .

Can I use Axios in laravel?

Just follow the following steps and make Axios HTTP get request in laravel with vue js and pass data blade views or controller to vue component laravel: Step 1: Download Laravel Fresh Setup. Step 2: Setup Database Credentials. Step 3: Generate Fake Data.

How do I make HTTP requests with Axios?

A GET request can be made with Axios to “get” data from a server. The HTTP get request is performed by calling axios. get() . The get() method requires two parameters to be supplied to it.

How does Axios post work?

Axios POST JSON request A POST request is created with post method. Axios automatically serializes JavaScript objects to JSON when passed to the post function as the second parameter; we do not need to serialize POST bodies to JSON.


1 Answers

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>
like image 176
Abdalla Arbab Avatar answered Sep 22 '22 01:09

Abdalla Arbab