After doing some more research, I found a solution that worked for me:
My client runs on localhost:8080
, while the server is on localhost:8084
. This setup makes my POST request a "cross-site" request. To allow Axios to handle this properly, I needed to enable credentials and support for the CSRF token. Here’s how I configured it:
export let axiosInstance = Axios.create({
baseURL: apiURL,
});
// New lines to allow credentials and CSRF token handling
axiosInstance.defaults.withCredentials = true;
axiosInstance.defaults.withXSRFToken = true;
The line axiosInstance.defaults.withCredentials = true;
instructs Axios to include cookies and credentials in each request. Additionally, the line axiosInstance.defaults.withXSRFToken = true;
enables Axios to automatically add the X-XSRF-TOKEN
header in requests.
On the server side, I also needed to allow credentials by adding
@CrossOrigin(origins = "http://localhost:8080", allowCredentials = "true")
above my controller. This configuration ensures that the browser can send cookies with requests, but only if they originate from http://localhost:8080
, thereby enhancing security by restricting requests to that specific origin.