I'm developing web-app using create-react-app and Laravel. create-react-app runs dev project on localhost:3000, whereas laravel backend works on localhost:8080. This is part of my code:
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)
}
So, when I submit the form I'm getting 419 unknown status. I've read laravel docs and found that this happens, because POST request doesn't contain csrf token. Laradocs says (for axios):
If you are not using this library, you will need to manually configure this behavior for your application
But how to make same thing for create-react-app based project?
Put this in your main blade view
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, capture the csrf token value via JS And pass it in the headers
const token = document.head.querySelector('meta[name="csrf-token"]');
headers: {
"Content-Type": "application/json".
"X-CSRF-TOKEN'": token
},
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments