luckyframework / website

The Lucky website
https://luckyframework.org
37 stars 65 forks source link

Howto use Ajax calls using csrf token #188

Open snadon opened 4 years ago

snadon commented 4 years ago

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 commented 4 years ago

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();
paulcsmith commented 4 years ago

Thanks! That's super helpful

crimson-knight commented 3 years ago

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.