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

IT技术 reactjs laravel fetch-api
2022-07-18 01:33:07

我正在使用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 unknown status我已阅读 laravel 文档并发现会发生这种情况,因为 POST 请求不包含csrf令牌。Laradocs 说(对于 axios):

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

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

2个回答

把它放在你的主刀片视图中

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

然后,通过 JS 捕获 csrf 令牌值并将其传递到 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
         },
    });