我正在构建一个以 Django 作为后端的 React Native 应用程序。我已经在 React Native 中设置了登录屏幕,并在 Django 中使用rest_framework_simplejwt 配置了 JWT 身份验证。但是,我在尝试登录时遇到错误。
在登录屏幕内:
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);
}
};
在 Django 中,视图:
@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)
序列化器:
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)
我在settings.py中设置了cors,这样我就可以在我的机器上发出API请求:
INSTALLED_APPS = [
'corsheaders', # DEV ONLY
...
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # DEV ONLY
...
]
CORS_ALLOW_ALL_ORIGINS = True # DEV ONLY
我收到的错误是: 日志错误[TypeError:无法读取未定义的属性“状态”]
我尝试过的:
如何解决 TypeError: Cannot read property 'status' of undefined 错误并确保我的登录功能正常工作?
要将 React Native 连接到 Django 服务器,请在您的 IP 而不是本地主机上运行服务器。假设你的 IP 是 10.0.0.49
python manage.py runserver 10.0.0.49:8000
然后将前端请求更改为
const response = await axios.post("http://10.0.0.49:8080/api/token/", {
username,
password,
});
不久前我的 django rn 项目也遇到了这个问题,非常令人沮丧