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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@dzirtusss Please take a look at this.