Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincej's avatar
Level 15

419 Error: Adding CSRF to Axios Post Request ?

I am 100% new to Axios having come over from Ajax. I am also brand new to Vue, and I am getting a 419 error in the JS console when I attempt to POST a value into L8 through Axios inside Vue. This appears to be a missing CSRF token in the Axios header. I have looked across Laracasts and SO and tried a few things but so far have not got it right. The GET api call works fine

I do have the CSRF TOKEN in the header of my Blade file where in my Vue template is presented, but the CSRF token is not in the Axios post call. Where should the CSRF header go? Many thanks !

Here is my Axios code:


methods:{
          updateChild(child){
            this.changedChild = child;
            console.log(child.child_id,child.childFirstName, child.status)

            axios.post('https://kidsclub.site/upDateChild', {
              child_id: child.child_id,
              status: child.status
          })
          .then(function (response) {
              console.log(response);
            })
          .catch(function (error) {
            console.log(error);
            });
          },

          loadChildren:function (){
            axios.get('https://kidsclub.site/api/allChildren')
            .then((response)=>{this.Children = response.data.data; })
            .catch(function (error){
                console.log(error);
              }
             );
          },

       }

0 likes
28 replies
neilstee's avatar

@vincej you can do this in many ways, one is to add defaults :

on your blade or layout file:

<script type="text/javascript">      
  window.csrf_token = "{{ csrf_token() }}"
</script>

and in your js

axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN': window.csrf_token
};
neilstee's avatar

This will add a csrf token in all of your axios request so you don't need to worry about getting your csrf token appended in every request.

neilstee's avatar

the other way is to put it in the meta tag like:

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

then read in your js file like:

'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

which is almost the same thing as my first comment

vincej's avatar
Level 15

Thank you for your quick reply. I like the idea of your first one. However, I am still unclear where exactly I stick the code. I put it just under the opening script tag of my template, and it had no effect. So I assume has to go somewhere inside Axios?

neilstee's avatar

@vincej you should put it in your blade file, commonly this is placed in your layout blade file.

The reason you need to put it in the blade is because you are calling {{ csrf_token() }}

vincej's avatar
Level 15

Let I have the CSRF in my master blade file. I am unclear about your second statement:

and in your js

axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': window.csrf_token };

neilstee's avatar

or you are asking where to place this?

axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN': window.csrf_token
};

you can place this after the import in your bootstrap.js file like:

window.axios = require('axios');
window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN': window.csrf_token
};
neilstee's avatar

I guess you only need this:

window.axios.defaults.headers.common['X-CSRF-TOKEN'] = window.csrf_token;

window.csrf_token if you use the script idea

else replace that where you save your csrf token

then, of course, don't forget to compile your js

vincej's avatar
Level 15

Thank so far. I added the code to my 'boostrap.js' and i recompiled. Unfortunately this has generated a new error in the console:

Access to XMLHttpRequest at 'https://kidsclub.site/upDateChild' from origin 'https://www.kidsclub.site' has been blocked by CORS policy: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.

But I don't have x-csrf-token in my Cors policy:

  public function handle(Request $request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin','*') //https://Kidsclub.site
            ->header('Access-Control-Allow-Methods','GET, POST')
            ->header('Access-Control-Allow-Headers','Content-type,x-requested-with, Authorization');
    }

neilstee's avatar

@vincej this is not related to your original post which is the CSRF token.

Basically, you are trying to access your Laravel app in a different origin(domain). Is this expected or both your vue and laravel app lives on the same domain?

Also checkout that www that was appended to your https://kidsclub.site domain.

neilstee's avatar

Try to access your web page without www as well, that might help

neilstee's avatar

or you can be explicit and just append the X-CSRF-TOKEN:

->header('Access-Control-Allow-Headers','Content-type,x-requested-with, Authorization,X-CSRF-TOKEN');
vincej's avatar
Level 15

yes, my server is on DigitalOcean. I have the below code as with a * because my CORs policy refuses to recognise the initiator as given in the console log, so that is something else I need to fix, I can't leave it open like this.

Anyway Progress is being made! The orginal Cors error below is now gone:

Access to XMLHttpRequest at 'https://kidsclub.site/upDateChild' from origin 'https://www.kidsclub.site' has been blocked by CORS policy: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.

But I am back to the original error - ugh:

Failed to load resource: the server responded with a status of 419 (unknown status)

neilstee's avatar

Wait so you are saying this is 2 completely different Laravel Applications?

vincej's avatar
Level 15

No. My application is at DigitalOcean. I have been accessing it through this dialogue through ssh. You can look at it if you want.

neilstee's avatar

@vincej can you check the payload you are sending if it includes an X-CSRF-TOKEN?

neilstee's avatar

@vincej I also saw this in your code:

window.axios.defaults.headers.common = {
  'X-Requested-With': 'XMLHttpRequest',
  'X-CSRF-TOKEN': window.csrf_token
}

If you run window.csrf_token in the console, it says undefined.

But if you use $('meta[name="csrf-token"]').attr('content') this shows the token, so use this instead:

window.axios.defaults.headers.common = {
  'X-Requested-With': 'XMLHttpRequest',
  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
vincej's avatar
Level 15

Updated the code as you requested. Still the same error. Checked the Network XHR, and very curious there is nothing coming out in the panel. This tell me nothing is being transmitted. Odd. Bt way of reminder here is the axios POST:

methods:{
          updateChild(child){
            this.changedChild = child;
            console.log(child.child_id,child.childFirstName, child.status)

            axios.post('https://kidsclub.site/upDateChild', {
              child_id: child.child_id,
              status: child.status
          })
          .then(function (response) {
              console.log(response);
            })
          .catch(function (error) {
            console.log(error);
            });
          },

I tried adding www to the url as Cronix suggested in another post to no avail. Thank you for sticking with this. That is very good of you!

vincej's avatar
Level 15

Maybe I should rip AXIOS out and replace it with Ajax. At least I have a bit of a better idea as to what I am doing with Ajax :o)

neilstee's avatar

Also saw this approach:

window.axios.defaults.headers['crossDomain'] = true;
window.axios.defaults.headers['Access-Control-Allow-Origin'] = '*';

Might help you once you're back.

vincej's avatar
Level 15

Heah Neil, I am going to have to call it a night and this this up again tomorrow AM. My dog is bursting to pee and has not been out in 10 hours poor thing.

Many thanks again for sticking with this. It is a mystery!

Cheers

vincej's avatar
Level 15

You are not going to believe this. Soon after I cam e in I googled "Axios with Vue" and I found an article which simple said, add to your bootstrap.js

https://serversideup.net/configuring-axios-globally-with-vuejs/

window.axios = require('axios');

I did that and Bingo, Happiness!

Thank you for all your help. You deserve a gold medal. btw, were are you? You must be west coast or else you don't sleep. I am north of Montana in Alberta Canada.

So all I have to do now is tighten up my Cors policy. I'll dig around and then create a fresh Q for that if need be.

Cheers!

neilstee's avatar

@vincej I don't understand how that works, I believe I already said this in my previous replies.

Anyways, glad it works already!

I'm from Manila, Philippines 🇵🇭 and upon checking your time, you are the one who doesn't sleep! 😅

Please or to participate in this conversation.