How to setup CSRF in JavaScript for laravel?

2020-08-08 04:35发布

问题:

I only use JavaScript.

And i know jQuery will set's the CSRF by,

  $(function() {
   $.ajaxSetup({
     headers: {
       'X-CSRF-Token': $('meta[name="_token"]').attr('content')
    }
  });
});

But how could i use "CSRF-Token" in JavaScript ?

Is there any possibilities for common setup for all Ajax Call ?

回答1:

To use csrf token common for all the ajax calls you have put following code in your master layout blade file.

In layout header:

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

In your layout footer:

    <script type="text/javascript">   
    jQuery(document).ready(function() {       
        jQuery.ajaxSetup({        
            headers: {            
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')        
            }    
        });    
    });
</script>

This will work for all your ajax requests.

Thanks



回答2:

You can include layout header look same above

But if you want use pure javascript to include token you can use:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", url , true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.setRequestHeader("X-CSRF-TOKEN", document.head.querySelector("[name=csrf-token]").content );
xhttp.send(params);

Hope to help your code ^^