Skip to content

Instantly share code, notes, and snippets.

@stoivo
Created May 19, 2017 10:26
Show Gist options
  • Select an option

  • Save stoivo/c019979d0443b15ece8bbb33340f34c5 to your computer and use it in GitHub Desktop.

Select an option

Save stoivo/c019979d0443b15ece8bbb33340f34c5 to your computer and use it in GitHub Desktop.

Revisions

  1. stoivo renamed this gist May 19, 2017. 1 changed file with 2 additions and 2 deletions.
    Original file line number Diff line number Diff line change
    @@ -10,8 +10,8 @@

    console.log("csrf-token: " + document.querySelector("meta[name=csrf-token]").getAttribute("content"))

    To test that it works
    var xhr = new XMLHttpRequest();
    // To test that it works
    // var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/v1/events', true);
    xhr.onload = function () {
    console.log("Request finished. Do processing here.");
  2. stoivo created this gist May 19, 2017.
    24 changes: 24 additions & 0 deletions add_csrf_token_to_request.elm
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@

    (function(){
    var send = XMLHttpRequest.prototype.send,
    token = document.querySelector("meta[name=csrf-token]").getAttribute("content");
    XMLHttpRequest.prototype.send = function(data){
    this.setRequestHeader('X-CSRF-Token', token);
    return send.apply(this, arguments);
    }
    })();

    console.log("csrf-token: " + document.querySelector("meta[name=csrf-token]").getAttribute("content"))

    To test that it works
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/v1/events', true);
    xhr.onload = function () {
    console.log("Request finished. Do processing here.");
    };
    xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
    xhr.send('{"event":{"projectId":10,"users":[1,2]}}');

    // Thanks to Louis Simoneau & Rahul Trikha
    // Taken from there talk on Elm, at RubyConf AU 2017
    // https://youtu.be/Bd6DTg1uNe0?t=27m58s