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

Kia*_*aba 2 laravel reactjs fetch-api

我正在使用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)
}
Run Code Online (Sandbox Code Playgroud)

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

如果您不使用此库,则需要为您的应用程序手动配置此行为

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

Lui*_*oya 7

将其放入您的主刀片视图中

<meta name="csrf-token" content="{{ csrf_token() }}">
Run Code Online (Sandbox Code Playgroud)

然后,通过JS捕获csrf token值并将其传递到标头中

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

headers: {
  "Content-Type": "application/json",
  "X-CSRF-TOKEN": token
},
Run Code Online (Sandbox Code Playgroud)