Django 401(Unauthorized)使用axios发出PUT请求,但使用Postman

k97glaaz  于 7个月前  发布在  iOS
关注(0)|答案(1)|浏览(84)

我试图从react端更新Django中的User。同样的功能已经通过Postman进行了测试。但是当我试图在react.js中使用Axios发出请求时,Django不接受它。并抛出401错误。

[23/Feb/2022 02:32:11] "PUT /api/v1/accounts/user-profile-update/ HTTP/1.1" 401 58

字符串
在postman上,我使用Bearer Token进行授权。我在headers config中传递了相同的令牌。

// Related Action Code
    const userData = JSON.parse(localStorage.getItem('userData'))

    const config = {
        headers: {
            'Content-type': 'application/json',
            Authorization: `Bearer ${userData.token}`
    }
    const { data } = await axios.put(
        `/api/v1/accounts/user-profile-update/`,
        config
    )


编辑:相关API视图:

@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def updateUserProfile(request):
    data = request.data
    user = request.user
    serializer = UserSerializerWithToken(user, many=False)

    user.name = data['name']
    user.phoneNumber = data['phoneNumber']
    user.city = data['city']
    user.postalCode = data['postalCode']
    user.country = data['country']
    user.save()

    return Response(serializer.data)


Django服务器上的两种不同响应:使用Postman

[23/Feb/2022 02:14:16] "PUT /api/v1/accounts/user-profile-update/%0A HTTP/1.1" 200 1182


使用React前端

[23/Feb/2022 02:32:11] "PUT /api/v1/accounts/user-profile-update/ HTTP/1.1" 401 58


有人能找出原因吗?以及如何解决这个问题。
编辑:注意事项:这个问题只发生在PUT或PATCH请求和GET请求上。我仍然无法弄清楚为什么会发生这种情况。如果我使用相同的token并使用Postman测试我的视图,它们绝对可以正常工作,但不使用react-redux设置。

hmae6n7t

hmae6n7t1#

你将头作为第二个参数传递,而在put()方法中,第一个参数是url,第二个是要发送的数据/有效负载,第三个是头。像这样使用axios.put('url',data,{ headers});

相关问题