| 1 |
// make GET request to backend on page load in order to obtain |
| 2 |
// a CSRF Token and load it into the Axios instance's headers |
| 3 |
// https://github.com/axios/axios#creating-an-instance |
| 4 |
const initializeAxiosInstance = async (url) => { |
| 5 |
try { |
| 6 |
let resp = await axios.get(url, {withCredentials: true}); |
| 7 |
console.log(resp); |
| 8 |
document.getElementById("get-request-full-response").innerHTML = JSON.stringify(resp); |
| 9 |
|
| 10 |
let csrfToken = parseCSRFToken(resp); |
| 11 |
console.log(csrfToken); |
| 12 |
document.getElementById("get-response-csrf-token").innerHTML = csrfToken; |
| 13 |
|
| 14 |
return axios.create({ |
| 15 |
// withCredentials must be true to in order for the browser |
| 16 |
// to send cookies, which are necessary for CSRF verification |
| 17 |
withCredentials: true, |
| 18 |
headers: {"X-CSRF-Token": csrfToken} |
| 19 |
}); |
| 20 |
} catch (err) { |
| 21 |
console.log(err); |
| 22 |
} |
| 23 |
}; |
| 24 |
|
| 25 |
const post = async (axiosInstance, url) => { |
| 26 |
try { |
| 27 |
let resp = await axiosInstance.post(url); |
| 28 |
console.log(resp); |
| 29 |
document.getElementById("post-request-full-response").innerHTML = JSON.stringify(resp); |
| 30 |
} catch (err) { |
| 31 |
console.log(err); |
| 32 |
} |
| 33 |
}; |
| 34 |
|
| 35 |
// general-purpose func to deal with clients like Axios, |
| 36 |
// which lowercase all headers received from the server response |
| 37 |
const parseCSRFToken = (resp) => { |
| 38 |
let csrfToken = resp.headers[csrfTokenHeader]; |
| 39 |
if (!csrfToken) { |
| 40 |
csrfToken = resp.headers[csrfTokenHeader.toLowerCase()]; |
| 41 |
} |
| 42 |
return csrfToken |
| 43 |
} |
| 44 |
|
| 45 |
const url = "http://localhost:8080/api"; |
| 46 |
const csrfTokenHeader = "X-CSRF-Token"; |
| 47 |
initializeAxiosInstance(url) |
| 48 |
.then(axiosInstance => { |
| 49 |
post(axiosInstance, url); |
| 50 |
}); |