Ошибка разбора JSON: Нераспознанный токен '<' при запросе/постинге данных с помощью react-native и django
Я только что начал создавать фронтенд react-native и бэкенд-приложение Django, и я пытался делать запросы от react native к серверу Django, но получил "JSON Parse error: Unrecognized token '<'". Я предполагаю, что это вызвано ошибкой в коде API, но я не смог разобраться в этом. Вот мой код:
views.py-
from django.shortcuts import render
from rest_framework import viewsets, status
from .serializers import UserSerializer, ProfileSerializer
from .models import Profile
from rest_framework.response import Response
from rest_framework.decorators import action
from django.contrib.auth.models import User
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.permissions import IsAuthenticatedOrReadOnly, BasePermission
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
@csrf_exempt
def login(request):
if request.method == 'POST':
valid = False
if 'username' in request.data:
username = request.data['username']
password = request.data['password']
user = authenticate(username=username, password=password)
if user is not None:
valid = True
else:
valid = False
elif request.method == 'GET':
valid = True
data = {
'valid': valid,
}
return JsonResponse(data)
login.js-
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, FlatList, Image, Button, Pressable, ScrollView } from 'react-native';
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome';
import { faStar } from '@fortawesome/free-solid-svg-icons'
import React, {useState, useEffect} from 'react'
import { TextInput } from 'react-native-gesture-handler';
import AsyncStorage from '@react-native-async-storage/async-storage';
export default function Login(props) {
const message = props.navigation.getParam('message', null)
const [ valid, setValid ] = useState("")
const [ username, setUsername ] = useState("")
const [ password, setPassword ] = useState("")
const val = () => {
if(valid.valid) {
props.navigation.navigate("MovieList")
} else {
var message = True
props.navigation.navigate("Login", {message: message})
}
}
const check = () => {
fetch('http://192.168.5.213:8000/home/login/', {
method: 'GET',
headers: {
}
})
.then( res => res.json())
.then( jsonRes =>
setValid(jsonRes)
)
.catch( error => console.log(error))
};
const log = () => {
fetch(`http://192.168.5.213:8000/home/login/`, {
method: 'POST',
headers: {
"Content-Type": 'application/json'
},
body: JSON.stringify({ username: username, password: password}),
})
.then( res => res.json())
.then( res => {
() => check()
})
.catch( error => console.log(error))
}
const sign = () => {
props.navigation.navigate("Signup")
}
return (
<View style={styles.container}>
<ScrollView style={styles.scroll} >
<Text style={styles.label}>
Username:
</Text>
<TextInput style={styles.input} placeholder="Username"
onChangeText={ text => setUsername(text)} value={username} />
<Text style={styles.label}>Password:</Text>
<TextInput style={styles.input} placeholder="Password" onChangeText={ text => setPassword(text)}
value={password}
/>
<Text style={styles.error}>{message}</Text>
<Button onPress={ () => log()} title="Login"></Button>
</ScrollView>
<View style={styles.footer}>
<Button onPress={ () => sign()} title="Don't have an acount? Sign up now" />
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#999',
},
scroll: {
backgroundColor:'#'
},
footer: {
borderTopColor: '#fff',
padding:35,
},
label: {
fontSize: 24,
color: "white",
padding: 10,
},
input: {
fontSize: 24,
backgroundColor: "white",
padding: 10,
margin: 10,
borderRadius: 5,
},
});
Как я могу решить эту проблему?