-
-
Save kevgathuku/684de19b0ec84fb05e24806c52baf707 to your computer and use it in GitHub Desktop.
React / Redux fetch from rails server with CSRF token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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