I am trying to send current logged in username from django backend to React frontend. I have created an endpoint currentuser/ that works perfectly fine in backend, it returns the expected result but when I call this api endpoint in React using axios,null value is returned there.
Here's the code for backend
#view.py
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.views import APIView
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username')
class LoggedInUserView(APIView):
def get(self, request):
serializer = UserSerializer(request.user)
return Response(serializer.data)
#urls.py
urlpatterns = [
path('currentuser/', views.LoggedInUserView.as_view(), name='currentuser'),
]
Here's the result when calling the api directly
Here's the code for frontend
class App extends React.Component {
state = {
users: [],
}
getUsers() {
axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.get(`http://localhost:8000/currentuser/`)
.then(res => {
console.log("res :", res);
const user = res.data;
console.log("response from backend", user);
this.setState({ users: user });
console.log(this.state.users);
})
.catch(err => {
console.log("error:", err);
});
console.log(this.state.users);
}
constructor(props) {
super(props);
this.getUsers();
}
render() {
return (.....)
}
};
export default App;
Here's the result when calling the api from the frontend
Any suggestions would be appreciated