Skip to content

Instantly share code, notes, and snippets.

@KamaMakh
Last active December 10, 2020 11:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KamaMakh/e0a86c9ccf3873427bf124ab2bcec14e to your computer and use it in GitHub Desktop.
Save KamaMakh/e0a86c9ccf3873427bf124ab2bcec14e to your computer and use it in GitHub Desktop.
axios template
let axios = require("axios")
let axiosInstance = axios.create({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
transformRequest: [(data, headers) => {
headers["Accept-Language"] = "en";
if (/* token */) {
headers["Authorization"] = "Bearer " + token
}
if (typeof data === "string") {
try {
data = JSON.parse(data);
} catch (e) {
/* Ignore */ }
}
return data;
}, ...axios.defaults.transformRequest],
validateStatus: function (status) {
if (status === 401 && document.location.href.indexOf("/auth") < 0) {
// no auth
} else if (
token && document.location.href.indexOf("/auth") > -1) {
// go to main
} else {
return true;
}
}
/* other custom settings */
});
axiosInstance.interceptors.response.use(
response => {
const res = response
if (res.status !== 200 && res.status !== 201) {
//error
} else {
return res
}
},
error => {
// reject
}
)
export default axiosInstance;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment