Laravel 是使用 axios 时需要的 csrf_field()

Laravel is csrf_field() needed in form when using axios

我想知道当我使用 Axios 在该表单上执行 ajax post 请求时是否需要在我的 <form> 中包含 {{ csrf_field() }}

在我的 bootstrap 中,我已经像这样设置了某种 csrf 保护:

//Add headers to axios
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
  window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
  console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

// html

<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">

不,当您将 CRSF-token 添加到 axios headers 时,无需在表单中包含 crsf_field。它附加在所有 headers 上,因为它已经添加到 axios default headers.