Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with CSRF token in JavaScript via Fetch API

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))
})
like image 822
Azizbek Nayimov Avatar asked May 12 '26 10:05

Azizbek Nayimov


1 Answers

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))
})
like image 196
Basant Singh Avatar answered May 13 '26 23:05

Basant Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!