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.