Unable to send messages via React frontend and POST requests fail on Django REST API panel

I am building a chat application using React for the frontend and Django for the backend. I am facing the following two issues:

  1. Issue with sending messages in React:
    When I try to send a message through the React app, I receive a 400 Bad Request error. The API request is made to the backend using a POST request, but the response indicates that there was a problem. The error message doesn't provide much insight, and I cannot send the message.

  2. Issue with POST request in Django REST API panel:
    When I try to make a POST request from the Django REST framework interface (admin panel) to send a chat message, the request seems to go through successfully but redirects to a blank page (without an error). The data is not posted, and nothing changes on the frontend. However, when I use curl to send the same request, it works fine.

Here’s a snippet of the relevant React code for sending messages:

const handleSendMessage = async () => {
    if (message.trim() || file) {
        setSendingMessage(true);
        const formData = new FormData();
        formData.append('receiver', selectedContact.id);
        formData.append('content', message);
        if (file) formData.append('file', file);

        try {
            const response = await fetch(`http://127.0.0.1:8000/api/chat/${userData?.current_basic_user?.username}/`, {
                method: 'POST',
                headers: {
                    "Authorization": `Bearer ${token}`,
                },
                body: formData,
            });
            
            if (!response.ok) {
                console.error('Failed to send message:', response.statusText);
            }
            const responseData = await response.json();
            setChatHistory((prevMessages) => [...prevMessages, responseData]);
            setMessage('');
            setFile(null);
        } catch (error) {
            console.error("Error sending message:", error);
        } finally {
            setSendingMessage(false);
        }
    }
};

And here's the backend code for the POST request:

class ChatSingleView(APIView):
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]  # To handle file uploads

    def get(self, request, username):
        try:
            # Get the current user's profile
            current_basic_user = request.user
            current_basic_user_profile = BasicUserProfile.objects.get(user=current_basic_user)

            # Get the receiver profile by username
            receiver_user = User.objects.get(username=username)
            receiver_profile = BasicUserProfile.objects.get(user=receiver_user)

            # Get the chat history between the current user and receiver
            chat_history_feed = Chat.objects.filter(
                sender=current_basic_user_profile, reciever=receiver_profile
            ) | Chat.objects.filter(
                sender=receiver_profile, reciever=current_basic_user_profile
            )

            # Serialize the chat history
            chat_serializer = ChatSerializer(chat_history_feed, many=True)

            # Return the chat history in response
            return Response({
                "chat_history_feed": chat_serializer.data
            }, status=status.HTTP_200_OK)

        except ObjectDoesNotExist:
            return Response({"error": "Receiver profile or chat history not found."}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({"error": f"An unexpected error occurred: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def post(self, request, username):
        try:
            # Get the current authenticated user's profile
            current_basic_user = request.user
            current_basic_user_profile = BasicUserProfile.objects.get(user=current_basic_user)

            # Get the receiver profile based on username
            receiver_user = User.objects.get(username=username)
            receiver_profile = BasicUserProfile.objects.get(user=receiver_user)

            # Extract content and receiver ID from request data
            content = request.data.get("content")
            receiver_id = request.data.get("receiver")  # This is the receiver id sent from frontend

            # Log received values for debugging
            print(f"Received content: {content}, receiver_id: {receiver_id}, file: {request.FILES.get('file')}")

            # Ensure required fields are present
            if not content or not receiver_id:
                return Response({"error": "Content and receiver are required."}, status=status.HTTP_400_BAD_REQUEST)

            # Validate the receiver ID - this might need to match the profile id
            if receiver_profile.id != int(receiver_id):
                return Response({"error": "Receiver ID mismatch."}, status=status.HTTP_400_BAD_REQUEST)

            # Handle the file upload (optional)
            file = request.FILES.get("file", None)

            # Create the chat message instance
            chat_message = Chat(
                sender=current_basic_user_profile,
                reciever=receiver_profile,
                content=content,
                creation_date=timezone.now().date(),  # Ensure it's just the date part
                file=file
            )

            # Save the chat message
            chat_message.save()

            # Serialize and return the created chat message
            chat_serializer = ChatSerializer(chat_message)
            return Response(chat_serializer.data, status=status.HTTP_201_CREATED)

        except ObjectDoesNotExist:
            return Response({"error": "Receiver profile not found."}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            # Log the exception message
            print(f"Unexpected error: {str(e)}")
            return Response({"error": f"An unexpected error occurred: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

What I’ve tried:

  • I checked the request headers and data and they seem correct.
  • I have successfully posted messages using curl, so the API itself works fine.
  • I ensured the correct token is sent in the request headers.
  • I verified that the backend is properly handling the POST request.

Any insights on why this is happening or what I might be missing?
Thank you for your help!

Вернуться на верх