Last active
June 7, 2023 11:29
-
-
Save mp035/ae833b68cb45f51dbac7a2520731d22a to your computer and use it in GitHub Desktop.
Replace axios requests with fetch interface.
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
//This adds axios.get, axios.post, axios.put, and axios.delete compatible methods to | |
//the global namespace. It is intened for json transactions. | |
let token = document.head.querySelector('meta[name="csrf-token"]'); | |
class HTTPError extends Error { | |
constructor(response, ...params) { | |
// Pass remaining arguments (including vendor specific ones) to parent constructor | |
super(...params); | |
this.response = response; | |
// Maintains proper stack trace for where our error was thrown (only available on V8) | |
if (Error.captureStackTrace) { | |
Error.captureStackTrace(this, HTTPError); | |
} | |
this.name = 'HTTPError'; | |
} | |
} | |
window.axios = {}; | |
['get','post','put','delete'].forEach(val => { | |
window.axios[val] = function (url, data){ | |
return fetch(url, { | |
headers: { | |
"Content-Type": "application/json", | |
"Accept": "application/json", | |
//"X-Requested-With": "XMLHttpRequest", | |
"X-CSRF-Token": token.content | |
}, | |
method: val, | |
credentials: "same-origin", | |
body: JSON.stringify(data), | |
}) | |
.then( async response=>{ | |
if (!response.ok) { | |
let data=await response.json(); | |
response.data = data; | |
console.log(response); | |
throw new HTTPError(response, response.statusText); | |
} | |
return response; | |
}).then(response=>{ | |
return response.json(); | |
}).then(jsonResponse => { | |
return {data:jsonResponse}; | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment