Skip to content

Instantly share code, notes, and snippets.

@xuannghia
Last active May 28, 2019 10:04
Show Gist options
  • Save xuannghia/a7ec2c6a63e2d1911aeffec92f788a95 to your computer and use it in GitHub Desktop.
Save xuannghia/a7ec2c6a63e2d1911aeffec92f788a95 to your computer and use it in GitHub Desktop.
Send requests with axios include xsrf token (Reactjs)
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