问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/63338231/laravel-automatically-send-csrf-token-with-requests-in-vanilla-js