Last active
July 29, 2020 07:01
-
-
Save fdidron/2c57b771b41fc77cca7fe6f183a746a6 to your computer and use it in GitHub Desktop.
Rails API wrapper with Authenticity 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
//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