Created
October 15, 2018 09:55
-
-
Save vinayakkulkarni/5fcb4fc65099490dc2ab0d6231ab8c6e to your computer and use it in GitHub Desktop.
API Middleware using axios
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
class Api { | |
constructor() {} | |
call(requestType, url, data = null) { | |
return new Promise((resolve, reject) => { | |
axios[requestType](url, data) | |
.then((response) => { | |
resolve(response); | |
}) | |
.catch(({ response, request, message }) => { | |
if (response) { | |
// The request was made and the server responded with a status code | |
// that falls out of the range of 2xx | |
// console.log(response.data); | |
// console.log(response.status); | |
// console.log(response.headers); | |
if (response.status === 401) { | |
// If you're using a auth middleware | |
// just perform logout() operation | |
// auth.logout(); | |
} | |
} else if (request) { | |
// The request was made but no response was received | |
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of | |
// http.ClientRequest in node.js | |
console.log('error.request: ', request); | |
} else { | |
// Something happened in setting up the request that triggered an Error | |
console.log('error.message: ', message); | |
} | |
reject(response); | |
}); | |
}); | |
} | |
} | |
export default Api; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In your
main.js
, register the Api class by attaching it to the window object.something like this:
In your Vuex actions or want to perform any XHRs: