简体   繁体   中英

Laravel: Automatically send CSRF token with requests in vanilla JS

I use a package installed with Composer in my Laravel project. It contains some JS code for file uploads. In at least one case, the uploads fail because there is no CSRF token sent with the request.

I hope to solve this problem without editing the vendor code. This is the relevant JS:

self.upload = function (file, filename) {
  var formData = new FormData();
  formData.append('file', file, filename);
  formData.append('field', JSON.stringify(field));
  formData.append('contentId', H5PEditor.contentId || 0);

  // Submit the form
  var request = new XMLHttpRequest();
  request.upload.onprogress = function (e) {
    if (e.lengthComputable) {
      self.trigger('uploadProgress', (e.loaded / e.total));
    }
  };

  // ...

}

Is there a way to make Laravel automatically send a CSRF token with a request like this?

With Axios, I'd do

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

With jQuery, I'd do

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

But in my case, no such library is used.

You need to have

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

in your page

and then in your code you can use the query selector

document.querySelector('meta[name="csrf-token"]')['content']

to get the value, please use the "fetch" api, so you can append the header.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Headers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM