如何获取 Laravel CSRF 令牌以通​​过 React 中的 fetch post 请求发送它?

How to get Laravel CSRF-token for sending it through fetch post request in React?

我正在使用 create-react-app 和 Laravel 开发网络应用程序。 create-react-app 在 localhost:3000 上运行开发项目,而 laravel 后端在 localhost:8080 上运行。这是我的代码的一部分:

const onSubmit = (e) => {
    e.preventDefault();

    const val = rootRef(formRef); // React ref to form
    
    // form data
    const data = {
        firstName: val('firstName'),
        lastName: val('lastName'),
        facultyId: val('facultyId'),
        departmentId: val('departmentId'),
        courseNo: val('courseNo'),
        phoneNumber: val('phoneNumber'),
        emailInput: val('email'),
        password: val('password')
    }

    const request = {
        method: "POST",
        // mode:   "cors",
        // cache:  "no-cache",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
    }

    fetch('http://localhost:8080/signup', request)
        .then(res => res.json())
        .then(console.log)
}

因此,当我提交表单时,我收到 419 未知状态。我已阅读 laravel 文档并发现会发生这种情况,因为 POST 请求不包含 csrf 令牌。 Laradocs 说(对于 axios):

If you are not using this library, you will need to manually configure this behavior for your application

但是如何为基于 create-react-app 的项目做同样的事情?

将此放在您的主 blade 视图中

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

然后,通过JS抓取csrf token值并传入headers

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

headers: {
  "Content-Type": "application/json",
  "X-CSRF-TOKEN": token
},

这是一个工作示例

<meta name="csrf-token" content="{{ csrf_token() }}">
 const token = document.head.querySelector('meta[name="csrf-token"]').content;

 fetch('/url', {
        method: 'post',
        body : JSON.stringify({
            key: 'value'
        }),
         headers: {
             "Content-Type": "application/json",
             "X-CSRF-TOKEN'": token
         },
    });