Created
January 24, 2020 16:58
-
-
Save valdergallo/1bbcd33bdf0ffbabebc99deaf03b06f9 to your computer and use it in GitHub Desktop.
default function to send and and load data from server
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
// Example POST method implementation: | |
// ajaxData(`http://example.com/answer`, {answer: 42}) | |
// .then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call | |
// .catch(error => console.error(error)); | |
function getCookie(name) { | |
let cookieValue = null; | |
if (document.cookie && document.cookie !== '') { | |
const cookies = document.cookie.split(';'); | |
for (let i = 0; i < cookies.length; i += 1) { | |
const cookie = cookies[i].trim(); | |
// Does this cookie string begin with the name we want? | |
if (cookie.substring(0, name.length + 1) === `${name}=`) { | |
cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); | |
break; | |
} | |
} | |
} | |
return cookieValue; | |
} | |
function queryParams(params) { | |
return Object.keys(params) | |
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`) | |
.join('&'); | |
} | |
export const ajaxData = function(url = '', data = {}, method = 'POST') { | |
// Default options are marked with * | |
const bareToken = localStorage.getItem('token'); | |
const baseAuth = localStorage.getItem('baseAuth'); | |
const csrfToken = getCookie('csrftoken'); | |
// add headers | |
const baseHeaders = new Headers(); | |
baseHeaders.append('Content-Type', 'application/json; charset=utf-8'); | |
baseHeaders.append('Accept', 'application/json'); | |
if (csrfToken) { | |
baseHeaders.append('X-CSRFToken', csrfToken); | |
} | |
// try use baseAuth by default | |
if (!baseAuth) { | |
baseHeaders.append('Authorization', `Token ${bareToken}`); | |
} else { | |
baseHeaders.append('Authorization', `Basic ${baseAuth}`); | |
} | |
const requestData = { | |
method, // *GET, POST, PUT, DELETE, etc. | |
mode: 'cors', // no-cors, cors, *same-origin | |
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached | |
credentials: 'same-origin', // include, same-origin, *omit | |
headers: baseHeaders, | |
redirect: 'follow', // manual, *follow, error | |
referrer: 'no-referrer', // no-referrer, *client | |
body: JSON.stringify(data), // body data type must match "Content-Type" header | |
}; | |
if (data === {}) { | |
delete requestData.body; | |
} | |
if (['GET'].indexOf(method) > -1) { | |
url += `?${queryParams(data)}`; | |
delete requestData.body; | |
} | |
// parses response to JSON | |
return fetch(url, requestData) | |
.then(res => { | |
return res.json(); | |
}) | |
.catch(err => { | |
console.error(err); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment