Skip to content

Instantly share code, notes, and snippets.

@pshoukry
Created March 6, 2017 14:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save pshoukry/4b0f246a6a52b07dac3b75cca76c7e76 to your computer and use it in GitHub Desktop.
Save pshoukry/4b0f246a6a52b07dac3b75cca76c7e76 to your computer and use it in GitHub Desktop.
React / Redux fetch from rails server with CSRF token
import _ from 'underscore';
import fetch from 'isomorphic-fetch'
class API {
getCSRFToken() {
return _.find(document.getElementsByTagName('meta'), (meta) => {
return meta.name === 'csrf-token'
}).content
}
get = (url) => {
return fetch(url, {credentials: 'same-origin'})
}
post = (url, params) => {
return fetch(url, {
method: 'POST',
body: JSON.stringify(params),
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': this.getCSRFToken(),
},
credentials: 'same-origin'
})
}
patch = (url, params) => {
return fetch(url, {
method: 'PATCH',
body: JSON.stringify(params),
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': this.getCSRFToken(),
},
credentials: 'same-origin'
})
}
}
export const api = new API;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment