Last active
May 28, 2019 10:04
-
-
Save xuannghia/a7ec2c6a63e2d1911aeffec92f788a95 to your computer and use it in GitHub Desktop.
Send requests with axios include xsrf token (Reactjs)
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
import axios from 'axios' | |
import React from 'react' | |
axios.defaults.xsrfHeaderName = 'X-CSRFToken' | |
axios.defaults.xsrfCookieName = 'csrftoken' | |
axios.defaults.withCredentials = true | |
const checkError = response => { | |
let status = response.status | |
if (status >= 400 && status < 500) { | |
return response.data | |
} | |
if (status >= 500) { | |
const errorText = (<div>Máy chủ đã xảy ra lỗi. Hãy thử lại sau nhé!</div>) | |
return { ok: false, msg: errorText } | |
} | |
} | |
const requests = { | |
get: (url, params) => { | |
return axios.get(url, { params }).then(response => { | |
return response.data | |
}).catch(error => { | |
return checkError(error.response) | |
}) | |
}, | |
post: (url, data) => { | |
return axios.post(url, data).then(response => { | |
return response.data | |
}).catch(error => { | |
return checkError(error.response) | |
}) | |
} | |
} | |
export default requests |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment