-1

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))
})
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • your csrf token must be saved somewhere in your backend (e.g session table), and then when page is generated, you echo the token to where X-CSRF-Token is supposed to be. The csrf token is then matched with what is in the backend to see if it's a valid session. – Someone Special Apr 18 '23 at 17:13
  • https://stackoverflow.com/a/31683058/2822041 – Someone Special Apr 18 '23 at 17:15
  • How you send a CSRF token to the server depends entirely on how the server expects it to be sent. There's no universal answer. (Sending a CSRF token to an API That expects a JSON content-type header seems pretty pointless though; you can't forget a request from a third party site with that header without bouncing off CORS). – Quentin Apr 18 '23 at 17:19

1 Answers1

0

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))
})
Basant Singh
  • 114
  • 2
  • 5