I’m sending the correct CSRF token to my backend, yet it keeps complaining that the token is incorrect.
With the help of useEffect hook I’m calling the getCsrfToken method once the component has loaded.
And then once I’m sending the form I send the CSRF token as part of the HTTP headers.
I’m using React + Vite in the FE and Nest in the BE.
I created a service to handle the API requests.
and with the help of useEffect hook I’m calling the getCsrfToken method once the component has loaded.
Service:
async getCsrfToken() {
try {
const result = await this.axios.get("/getCsrf");
if (result.status === 200) {
// UserServiceStore._csrfToken = result?.data?.CSRFToken;
this.axios.defaults.headers[
"X-CSRF-Token"
] = `${result?.data?.CSRFToken}`;
}
console.log(
result?.data?.CSRFToken,
"result?.data?.CSRFTokenresult?.data?.CSRFToken"
);
} catch (e) {
throw e;
}
// TODO: Adjust, need to return something to the FE
return "sssssssssss";
}
// TODO: finish
async register() {
const payload = {
username: "janeDoe",
email: "[email protected]",
password: "sasccvvc",
};
console.log(this.axios.defaults.headers, "Really");
console.log(this.axios.defaults.headers, "Really");
const result = await this.axios.post("/register", payload);
// this.axios.headers["X-CSRF-Token"] = result?.data?.CSRFToken;
console.log("AXIOSSSSSSSSS", result);
return "sssssssssss";
}
Nest Controller (Very basic):
@Get('getCsrf')
something(@Request() req: any) {
return { CSRFToken: req.csrfToken() };
}