I have a back in Django using Django Rest Framework during a post request I want an authorization token to be entered in order to know if the user is logged in to validate the request. But when in my front in React native, I put in the header the authorization with the token of the user but when I validate the request by pressing the button it goes into the catch and it tells me a 401 error so that I I don't have permission. Except when I do it with postman, I log in, I retrieve the token obtained and I put it in the authorization and I launch the same request I have a 201 status created.
Here is my code in React Native Front :
const submitButton = async () => {
if (!gardenName.trim()) {
alert("Veuillez renter un nom de jardin s'il vous plait!");
return;
}
setLoading(true);
try {
const jsonValue = await AsyncStorage.getItem("user");
const parsedUserData = JSON.parse(jsonValue) || {};
setUser(parsedUserData);
const data = new FormData();
data.append("user", parsedUserData.user.id);
data.append("name", gardenName);
const response = await axios.post(`${baseUrl}/garden/`, data, {
headers: {
Authorization: `Token ${parsedUserData.token}`,
"Content-Type": "multipart/form-data",
},
});
if (response.status === 201) {
alert(`Votre jardin ${gardenName} a bien été crée`);
setLoading(false);
setGardenName("");
//navigation.replace('BottomNavigation');
} else {
throw new Error("Erreur");
}
} catch (e) {
setLoading(false);
alert(e.message);
console.log(e);
}
};
I do not understand what is missing in the configuration of my Axios request, if you can enlighten me thank you!
did you update your INSTALLED_APPS like this;
INSTALLED_APPS = [
...
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
....
]
and also you must update your REST_FRAMEWORK settings. You should add this lines.
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),