Django后端-React前端:POST请求创建用户配置文件失败问题
React向Django后端创建用户配置文件失败排查
问题现象
通过React前端向Django后端发送POST请求创建用户配置文件时,流程未按预期运行。尽管已发送必要数据,但用户配置文件未成功创建。
相关代码
React侧代码
创建配置文件函数
let UserProfileCreation = async (formData, userId) => { try { const response = await fetch("http://127.0.0.1:8000/user-profile/", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${localStorage.getItem("authToken")}`, }, body: JSON.stringify({ user: userId, first_name: formData.name, last_name: formData.lastname, description: formData.txtname, phone_number: formData.number, // Include image fields if required: profile_picture, banner_picture }), }); if (response.ok) { return true; } else { return false; } } catch (error) { console.error("Error creating profile:", error); return false; } };
登录函数
let loginUser = async (e) => { e.preventDefault(); console.log("Form Submitted!"); let response = await fetch("http://127.0.0.1:8000/api/token/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username: e.target.username.value, password: e.target.password.value, }), }); let data = await response.json(); console.log(jwtDecode(data.access)); if (response.status === 200) { setAuthToken(data); setuser(jwtDecode(data.access)); localStorage.setItem("authToken", JSON.stringify(data)); const profileExists = await CheckProfile(jwtDecode(data.access).user_id); // Pass the user ID if (profileExists) { navigate("/"); } else { navigate("/continue-setup"); } } else { alert("Something went wrong"); } };
Django侧代码
视图类
class UserProfileView(generics.CreateAPIView): queryset = UseProfile.objects.all() serializer_class = UseProfileSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
模型类
class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') profile_picture = models.ImageField(upload_to="user/profile", null=True, blank=True) banner_picture = models.ImageField(upload_to="user/profile", blank=True, null=True) first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100, null=False) description = models.CharField(max_length=300, null=True) phone_number = models.IntegerField(null=True)
已完成的排查步骤
- 确认后端端点地址正确
- 验证React请求包含
Content-Type: application/json和Authorization: Bearer头,认证正常 - 检查请求负载数据格式无误
进一步排查与修复要点
修复视图模型拼写错误
视图中queryset = UseProfile.objects.all()存在拼写错误,模型类名为UserProfile,应改为queryset = UserProfile.objects.all()修正JWT令牌读取逻辑
React中localStorage存储的是整个令牌对象,Authorization头需要提取access字段,修改为:Authorization: `Bearer ${JSON.parse(localStorage.getItem("authToken")).access}`,捕获后端具体错误信息
修改React创建配置文件函数,打印后端返回的错误详情:if (!response.ok) { const errorData = await response.json(); console.error("Backend error:", errorData); return false; }检查序列化器配置
确认UseProfileSerializer中user字段使用PrimaryKeyRelatedField,允许通过用户ID关联,且所有必填字段都正确映射验证用户ID传递正确性
在UserProfileCreation函数中打印userId,确认与当前登录用户ID一致
内容的提问来源于stack exchange,提问作者Kaiox70
相关产品推荐
相关产品推荐

