Я продолжаю получать GET http://127.0.0.1:8000/room/f5428fc5 404 (Not Found):
Я делаю приложение Next.js и Django с Spotify api, и у меня проблемы с получением get-room api, когда я нажимаю на кнопку создания комнаты на странице create.js, комната создается и генерируется уникальный код, но комната не найдена. кто-нибудь может мне помочь?:
из страницы create.js
const handleRoomButtonPressed = () => {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
votes_to_skip: votesToSkip,
guest_can_pause: guestCanPause,
}),
};
fetch("/api/create-room", requestOptions) // Update the URL path
.then((response) => response.json())
.then((data) => router.push("/room/" + data.code))
.catch((error) => setErrorMsg("Error creating room..."));
};
const renderCreateButtons = () => {
return (
<div className="flex flex-col items-center mt-2">
<button
className=" bg-spotifyGreen text-white rounded-lg px-4 py-2 mb-2 hover:bg-spotifyLight "
onClick={handleRoomButtonPressed}
>
Create A Room
</button>
<button
className="bg-red-500 text-white rounded-lg px-4 py-2 hover:bg-red-400"
onClick={() => router.push("/")}
>
<ArrowBackIcon /> Back
</button>
</div>
);
};
со страницы room.js:
const [roomDetails, setRoomDetails] = useState({
votesToSkip: 2,
guestCanPause: false,
isHost: false,
spotifyAuthenticated: false,
song: {},
});
const { roomCode } = router.query;
const getRoomDetails = () => {
fetch("/api/get-room" + "?code=" + roomCode)
.then((response) => {
if (!response.ok) {
leaveRoomCallback();
navigate("/");
}
return response.json();
})
.then((data) => {
setRoomDetails({
votesToSkip: data.votes_to_skip,
guestCanPause: data.guest_can_pause,
isHost: data.is_host,
});
if (data.is_host) {
authenticateSpotify();
}
});
};
из api/urls:
from django.urls import path
from .views import RoomView, CreateRoomView, GetRoom, JoinRoom, UserInRoom, LeaveRoom, UpdateRoom
urlpatterns = [
path('room', RoomView.as_view()),
path('create-room', CreateRoomView.as_view()),
path('get-room', GetRoom.as_view()),
path('join-room', JoinRoom.as_view()),
path('user-in-room', UserInRoom.as_view()),
path('leave-room', LeaveRoom.as_view()),
path('update-room', UpdateRoom.as_view())
]
из api/views:
class GetRoom(APIView):
serializer_class = RoomSerializer
lookup_url_kwarg = 'code'
def get(self, request, format=None):
code = request.GET.get(self.lookup_url_kwarg)
if code is not None:
room = Room.objects.filter(code=code).first()
if room is not None:
data = RoomSerializer(room).data
data['is_host'] = self.request.session.session_key == room.host
return Response(data, status=status.HTTP_200_OK)
return Response({'Room Not Found': 'Invalid Room Code.'}, status=status.HTTP_404_NOT_FOUND)
return Response({'Bad Request': 'Code parameter not found in request'}, status=status.HTTP_400_BAD_REQUEST)
class CreateRoomView(APIView):
serializer_class = CreateRoomSerializer
def post(self, request, format=None):
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
guest_can_pause = serializer.data.get('guest_can_pause')
votes_to_skip = serializer.data.get('votes_to_skip')
host = self.request.session.session_key
code = str(uuid.uuid4())[:8]
room = Room(host=host, guest_can_pause=guest_can_pause, votes_to_skip=votes_to_skip, code=code)
room.save()
self.request.session['room_code'] = room.code
return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED)
return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST)
из api/models.py:
from django.db import models
import string
import random
def generate_unique_code():
length = 6
while True:
code = ''.join(random.choices(string.ascii_uppercase, k=length))
if Room.objects.filter(code=code).count() == 0:
break
return code
# Create your models here.
class Room(models.Model):
code = models.CharField(max_length=8, default="", unique=True)
host = models.CharField(max_length=50, unique=True)
guest_can_pause = models.BooleanField(null=False, default=False)
votes_to_skip = models.IntegerField(null=False, default=1)
created_at = models.DateTimeField(auto_now_add=True)
из frontend/urls:
from django.urls import path
from .views import RoomView, CreateRoomView, GetRoom, JoinRoom, UserInRoom, LeaveRoom, UpdateRoom
urlpatterns = [
path('room', RoomView.as_view()),
path('create-room', CreateRoomView.as_view()),
path('get-room', GetRoom.as_view()),
path('join-room', JoinRoom.as_view()),
path('user-in-room', UserInRoom.as_view()),
path('leave-room', LeaveRoom.as_view()),
path('update-room', UpdateRoom.as_view())
]
Я пробовал менять пути в fetch и все равно не получил никаких изменений.