Skip to content

Instantly share code, notes, and snippets.

@rescribet
Last active August 9, 2016 19:41
Show Gist options
  • Save rescribet/c62b865c6aa9f710531e to your computer and use it in GitHub Desktop.
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.
/**
*
* 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;
}
@anpr
Copy link

anpr commented Jun 29, 2016

I'd be happy to have this as part of react_on_rails. It's really a very common requirement.

@justin808
Copy link

@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