djangoreact-nativedjango-rest-framework-simplejwtdjango-cors-headers

Error while trying to connect Django With ReactNative


I am building a React Native app with Django as the backend. I have set up the login screen in React Native and configured JWT authentication with rest_framework_simplejwt in Django. However, I encounter an error when trying to log in.

Within the login screen:

    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const [error, setError] = useState("");

    const handleSubmission = async () => {
        try {
            const response = await axios.post("http://127.0.0.1:8080/api/token/", {
                username,
                password,
            });
            if (!response || !response.data) {
                throw new Error("Invalid server response");
            }
            await AsyncStorage.setItem("accessToken", response.data.access);
            await AsyncStorage.setItem("refreshToken", response.data.refresh);
            navigation.navigate("Tab");
        } catch (error) {
            console.error("error", error);
            const errorMessage = error.response && error.response.data && error.response.data.message
                ? error.response.data.message
                : "Whoops! Log In Failed, please try again later 😅.";
            setError(errorMessage);
        }
    };

In Django, views:

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_user(request):
    serializer = CreateUserSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response({'message': "Whoops! error while creating user 🫣", 'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

Serializers:

class CreateUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'password']

    def create(self, validated_data):
        validated_data['password'] = make_password(validated_data.get('password'))
        return super(CreateUserSerializer, self).create(validated_data)

and I set up cors in settings.py so that I can make API request on my machine:

INSTALLED_APPS = [
    'corsheaders', # DEV ONLY
    ...
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware', # DEV ONLY
    ...
]

CORS_ALLOW_ALL_ORIGINS = True # DEV ONLY

The error I'm getting is: LOG error [TypeError: Cannot read property 'status' of undefined]

What I've tried:

  1. Ensured corsheaders is installed and properly configured.
  2. Verified that the backend endpoint http://127.0.0.1:8080/api/token/ is correct and reachable.
  3. Logged the complete error object.

How can I resolve the TypeError: Cannot read property 'status' of undefined error and ensure that my login functionality works correctly?


Solution

  • To connect react native to django server, run the server on your ip instead of localhost. This assumes your ip is 10.0.0.49

    python manage.py runserver 10.0.0.49:8000
    

    Then change the frontend request to

    const response = await axios.post("http://10.0.0.49:8080/api/token/", {
                username,
                password,
            });
    

    I had this problem with my django rn project too a while back, very frustrating