'How to get Laravel CSRF-token for sending it through fetch post request in React?
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?
Solution 1:[1]
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"]').content;
headers: {
"Content-Type": "application/json",
"X-CSRF-TOKEN": token
},
Solution 2:[2]
Here is a working example
<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
},
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | reallynice |
| Solution 2 |
