React前端消息发送失败及Django REST API POST异常求助
React + Django 聊天应用问题排查求助
1. React前端消息发送问题
通过React应用发送消息时,收到400 Bad Request错误。API请求为POST请求,但响应无有效错误提示,无法完成消息发送。
2. Django REST API面板POST请求问题
在Django REST框架自带的API面板发起POST请求发送聊天消息时,请求看似成功但跳转到空白页面,数据未提交,前端无变化。但使用curl发送相同请求可正常工作。
React端发送消息代码片段
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); } } };
Django后端处理POST请求代码片段
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)
已尝试的排查步骤
- 检查请求头和数据格式,确认参数正确;
- 使用
curl发送请求可成功,说明API本身逻辑正常; - 确认请求头中携带了有效的认证token;
- 验证后端POST接口可正确处理请求。
希望大家帮忙分析问题原因或提供排查方向,感谢!
内容的提问来源于stack exchange,提问作者Abol
相关产品推荐
相关产品推荐

