我正在使用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的项目做同样的事情呢?