How to setup CSRF in JavaScript for laravel?

不想你离开。 提交于 2019-12-08 09:27:27

问题


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 ^^



来源:https://stackoverflow.com/questions/42383026/how-to-setup-csrf-in-javascript-for-laravel

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