I started to use django recently and I also tried to use React js and I wanted to do something simple like a nav var in React. I have accounts and log in implemented using django forms which work well. For the nav I would need to fetch the user information which I have on a DRF API as follows in the views file:
@api_view(['GET'])
@authentication_classes((SessionAuthentication, TokenAuthentication))
@ensure_csrf_cookie
@permission_classes((IsAuthenticated,))
def user_details_view(request, *args, **kwargs): #REST API for detailing some basic info about the user that is using the system at the moment
current_user = request.user
id = current_user.id
status = 200
try:
obj = CustomUser.objects.get(id=id)
data = UserSerializer(obj)
return Response(data.data, status=status)
except:
status = 404
return Response(status=404)
return Response(data.data, status=status)
The urls are set up and if I access it in the django server it works fine but when I try on react by:
function loadUserInfo(callback){
const xhr = new XMLHttpRequest();
const method = 'GET';
const url = "http://127.0.0.1:8000/userdetails/";
const responseType = "json";
xhr.responseType = responseType; // Let the xhr request know that its getting a json
xhr.open(method, url); //This opens the request with the method and url entered
xhr.onload = function(){
console.log("This is the response: ",xhr.response)
callback(xhr.response, xhr.status)
}
xhr.onerror = function(){
callback({"message":"The request was an error"}, 400)
}
xhr.send();//Trigger that request
}
I get:
GET http://127.0.0.1:8000/userdetails/ 403 (Forbidden)
This is the response: {detail: 'Authentication credentials were not provided.'}
How can I make React access the data? I only need to have some minor components made by react and also have it so that if I open it on another browser I can log in with a different user. I have looked into many resources but they do not seem to work for my case. I am using the django server.
You have to get the auth token in your react app. The token is generated once you log in to your Django from react app, and then you need to pass that token along with the get method.
axios
.get('http://www.exapmle.com', {
headers: {
Authorization: `Token ${props.token}`,
},
})
or in your Django app set the permission class as any for that model, or remove IsAuthenticated from the permission class.
permission_classes = [IsAuthenticated]