Last active
August 9, 2016 19:41
-
-
Save rescribet/c62b865c6aa9f710531e to your computer and use it in GitHub Desktop.
The helpers we use to aid in using fetch with secure and non-secure (json) calls.
This file contains 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
/** | |
* | |
* A regular non-safe get request: | |
* fetch('/profiles/foobar.json', jsonHeader()); | |
* | |
* How this would look in a safe fetch request: | |
* fetch('/profiles.json', safeCredentials({ | |
* method: 'POST', | |
* body: JSON.stringify({ | |
* q: input, | |
* thing: this.props.thing | |
* }) | |
* })); | |
* | |
* | |
*/ | |
/** | |
* For use with window.fetch | |
* @param {Object} options Object to be merged with jsonHeader options. | |
* @returns {Object} The merged object. | |
*/ | |
export function jsonHeader (options) { | |
options = options || {}; | |
return Object.assign(options, { | |
'Accept': 'application/json', | |
'Content-Type': 'application/json' | |
}); | |
} | |
/** | |
* Lets fetch include credentials in the request. This includes cookies and other possibly sensitive data. | |
* Note: Never use for requests across (untrusted) domains. | |
* @param {Object} options Object to be merged with safeCredentials options. | |
* @returns {Object} The merged object. | |
*/ | |
export function safeCredentials (options) { | |
options = options || {}; | |
return Object.assign(options, { | |
credentials: 'include', | |
mode: 'same-origin', | |
headers: Object.assign((options['headers'] || {}), authenticityHeader(), jsonHeader()) | |
}); | |
} | |
// Additional helper methods | |
export function authenticityHeader (options) { | |
options = options || {}; | |
return Object.assign(options, { | |
'X-CSRF-Token': getAuthenticityToken(), | |
'X-Requested-With': 'XMLHttpRequest' | |
}); | |
} | |
export function getAuthenticityToken () { | |
return getMetaContent('csrf-token'); | |
} | |
export function getMetaContent (name) { | |
const header = document.querySelector(`meta[name="${name}"]`); | |
return header && header.content; | |
} |
@justin808 I didn't get a notification for some reason. While I'd like to integrate the code, I don't think I could currently live up to the task in time constraints. However, looking through the code, I didn't see any references to .ajax nor fetch.
Would it require integration into existing code or just an aptly named file representing the module? Since that certainly would be doable.
I'd be happy to have this as part of react_on_rails. It's really a very common requirement.
@dzirtusss Please take a look at this.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@fletcher91: Any interest in submitting this as a PR to https://github.com/shakacode/react_on_rails/tree/master/node_package/src ?