website icon indicating copy to clipboard operation
website copied to clipboard

Howto use Ajax calls using csrf token

Open snadon opened this issue 6 years ago • 3 comments

We should add how to make ajax calls with the csrf token in the documentation. Something along the line of https://gist.github.com/benschwarz/5333009

snadon avatar Oct 19 '19 19:10 snadon

Here's how I handle it (I had to use jquery in that project):

// csrf.js
import $ from "jquery";

const Csrf = () => {
  const token = $("meta[name=\"csrf-token\"]").attr("content");
  $.ajaxSetup({
    beforeSend: (xhr) => {
      xhr.setRequestHeader("X-CSRF-Token", token);
    }
  });
};

export default Csrf;
// app.js
import Csrf from "./csrf.js";
Csrf();

snadon avatar Oct 23 '19 20:10 snadon

Thanks! That's super helpful

paulcsmith avatar Oct 23 '19 20:10 paulcsmith

Here's a non-jQuery version for JS submitting to end-points in Lucky. I use this in Stimulus controllers often.

let csrf_token = document.querySelector('[name="csrf-token"]').content
    
fetch('/path/in/your/app/', { 
        method: 'POST', 
        headers: { 'x-csrf-token': csrf_token }, 
        body: JSON.stringify({ // use valid JSON here to post anything }) 
}).then(response => response.json()) // Do whatever you want with the json response object here. 

Here's what a GET request would look like. I think you could also omit the "method: 'GET" part and just define the headers, but I prefer to be explicit about it.

let csrf_token = document.querySelector('[name="csrf-token"]').content
    
fetch('/path/in/your/app/', { 
        method: 'GET', 
        headers: { 'x-csrf-token': csrf_token }) 
}).then(response => response.json()) // Do whatever you want with the json response object here. 

crimson-knight avatar May 05 '21 19:05 crimson-knight