Skip to content

Instantly share code, notes, and snippets.

@kevgathuku
Forked from pshoukry/api.js
Created May 23, 2018 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevgathuku/684de19b0ec84fb05e24806c52baf707 to your computer and use it in GitHub Desktop.
Save kevgathuku/684de19b0ec84fb05e24806c52baf707 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