1

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

enter image description here

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

enter image description here

Any suggestions would be appreciated

Bickky Sahani
  • 351
  • 4
  • 13

1 Answers1

0

Just learning this topic now. Did you login on React front-end? If you just want to retrieve login user's profile. Here is my solution for your reference.

  • Firstly, I tried use simple-JWT authentication to set up react and Django. (google "JWT authentication Django and React", there are many many teaching materials).

  • Then to log in on react site, and from a response of Django you can retrieve the logged-in user detail. The response.data is a token, which means you can use a "jwt_decode" to get the information you want including: username, id, email. (may have security issue... refer to If you can decode JWT, how are they secure?, just for learning should be fine). Your code might look like the following:

axios.post("http://127.0.0.1:8000/token/", {
        username: username,
        password: password,
    })
     .then((response) => {
      let token = response.data.access;
      localStorage.setItem("token", token);
      let user_id = jwt_decode(response.data.access).user_id;
      ...
      localStorage.setItem("user_id", user_id);
        
    })
      
  • Once you got your user_id in localstorage, you can use it to retrieve all the details, your code might look like:
let id = parseInt(localStorage.getItem("user_id"));
const userDetail = (id) => {
const token = localStorage.getItem("token");
axios
  .get(`http://127.0.0.1:8000/users/${id}`, {
    headers: { Authorization: token },
  })
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });
  

The response.data includes all information you posted on your Django back-end API. Hope this helped.

Joanna
  • 81
  • 1
  • 6