Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Replace axios requests with fetch interface.
//This adds axios.get,, 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
this.response = response;
// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, HTTPError);
} = '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(); = data;
throw new HTTPError(response, response.statusText);
return 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
You can’t perform that action at this time.