通过 fetch api 发送带有 ajax 请求的 cookie

sending cookies with ajax request via fetch api

在 nodeJs 应用程序中,我通过 ajax 请求向服务器发送 multipart/form-data。我也在使用 csurf 包来防止 csrf 攻击

问题

当我在没有 ajax 请求的情况下提交我的表单时,一切正常,但是当我使用 ajax 请求提交我的表单时,我在服务器上收到 invalid csrf token 错误。

据我了解此错误的原因,这是因为 cookie 未随请求一起发送。

为了使用 ajax 请求发送 cookie,我在通过 fetch api 发出的 post 请求中设置了 credentials: 'same-origin',但这并没有解决问题。我也尝试设置 credentials: 'include' 但这没有任何区别。

问题

我的理解是否正确,这个问题是因为 cookie 没有随 ajax 请求一起发送,我该如何解决这个问题?

代码

let response = await fetch(requestUrl, {
      method: 'POST',
      credentials: 'include',
      headers: {
          'Content-Type': 'multiplart/form-data'
      },
      body: new URLSearchParams(form)
});

当使用 fetch()/AJAX 和 csurf 时,您需要将 CSRF 令牌作为请求传递 header:

// Read the CSRF token from a hidden input in the form
const token = document.querySelector('input[name="csrf-token"]').value;

// POST using the Fetch API
fetch('/<route.name>', {
  headers: {
    // pass the csrf token as a header
    'CSRF-Token': token
  },
  method: 'POST',
  body: {
    ...
  }
});