I haven't practiced using CSRF tokens in JavaScript. Now I need to send the token to the server. Can I use POST request of fetch API for this, and how it is done? (I only know JavaScript. I don't understand AJAX, jQuery etc.).
Do I need to write something in the HTML file for my weapon with the token? Running PHP Laravel for backend?
I have this code which gives me a 419 error:
form1.addEventListener('submit', (e) => {
e.preventDefault()
const formDatas = new FormData(form1);
const data = new URLSearchParams(formDatas);
fetch(f1_search_url, {
headers: {
"X-CSRF-Token": my_token, // 👈👈👈 Set the token
"Content-Type": "application/json"
},
method: 'POST',
body: data
}).then(res => res.json())
.then(data => console.log(data))
})
Use csrf-token in head meta tag
<meta name="csrf_token" content="{{ csrf_token() }}">
In Fetch Api need to add credentials: "same-origin"
<script>
const csrfToken = document.head.querySelector("[name~=csrf_token][content]").content;
form1.addEventListener('submit', (e) => {
e.preventDefault()
const formDatas = new FormData(form1);
const data = new URLSearchParams(formDatas);
fetch(f1_search_url, {
headers: {
"X-CSRF-Token": my_token, // 👈👈👈 Set the token
"Content-Type": "application/json"
},
method: 'POST',
credentials: "same-origin"
body: data
}).then(res => res.json())
.then(data => console.log(data))
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With