Here is my "login" function that I am using to authenticate users when they provide their credentials in NextJs website fronend:
export const login = (username, email, password) => async dispatch => {
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');
console.log(csrftoken);
const config = {
headers: {
'Content-Type': 'application/json',
}
};
const config_two = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
}
};
console.log(config_two)
const body = JSON.stringify({ email, password });
const body_two = JSON.stringify({ username, password });
try {
const res = await axios.post(`http://localhost:8000/auth/jwt/create/`, body, config);
const res_two = await axios.post(`http://localhost:8000/api-token-auth/`, body_two, config_two);
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
});
dispatch(load_user());
toast.success("You are logged in");
} catch (err) {
toast.error("Something went wrong");
dispatch({
type: LOGIN_FAIL
})
}
};
For one purpose I had to include another post request to get tokens from the database which are provided by rest_framework.authtoken.models when users are registered. However, when I try to run this function I receive the following error attached here (https://i.stack.imgur.com/Y9YNf.png) (https://i.stack.imgur.com/QWSb2.png).
It says that the csrf cookie is not provided, but I add it in the header in config_two constant that is sent with the request.
Looking forward to hearing possible solutions indicating on my mistakes. In advance, thank you for your time.
I read the documentation several times, watched videos in YouTube, but it didn't help. I am expecting it to accept my request and send me a token as a responce.