Laravel:在Vanilla JS中自动发送带有请求的CSRF令牌 [英] Laravel: Automatically send CSRF token with requests in vanilla JS

查看:154
本文介绍了Laravel:在Vanilla JS中自动发送带有请求的CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Laravel项目中使用随Composer安装的软件包.它包含一些用于文件上传的JS代码.在至少一种情况下,上传失败是因为没有与请求一起发送的CSRF令牌.

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.

我希望在不编辑供应商代码的情况下解决此问题.这是相关的JS:

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));
    }
  };

  // ...

}

是否有一种方法可以使Laravel自动发送带有此类请求的CSRF令牌?

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

我愿意使用Axios

With Axios, I'd do

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

我会使用jQuery

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.

推荐答案

您需要拥有

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

在您的页面中

然后在您的代码中可以使用查询选择器

and then in your code you can use the query selector

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

要获取该值,请使用获取"api,因此您可以附加标题.

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

这篇关于Laravel:在Vanilla JS中自动发送带有请求的CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆