Laravel: Automatically send CSRF token with requests in vanilla JS

落花浮王杯 提交于 2020-08-20 11:39:48

问题


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

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