Skip to content

Instantly share code, notes, and snippets.

@fdidron
Last active July 29, 2020 07:01
Show Gist options
  • Save fdidron/2c57b771b41fc77cca7fe6f183a746a6 to your computer and use it in GitHub Desktop.
Save fdidron/2c57b771b41fc77cca7fe6f183a746a6 to your computer and use it in GitHub Desktop.
Rails API wrapper with Authenticity token
//This assumes the following script tag exists in
// the layout/application.html.erb head:
//<script charset="utf-8" type="text/javascript">
// window.__APP_CONFIG__ = {};
// __APP_CONFIG__.csrfToken = '<%= form_authenticity_token %>';
//</script>
async function api(url, method = "GET", data = {}) {
const payload = { ...data, authenticity_token: __APP_CONFIG__.csrfToken };
const endpoint =
method === "GET" && payload
? `${url}?${new URLSearchParams(payload).toString()}`
: url;
const body =
method !== "GET"
? JSON.stringify({
...payload,
authenticity_token: __APP_CONFIG__.csrfToken
})
: null;
const res = await fetch(endpoint, {
method,
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body
});
return res.json();
}
export default api;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment