Faisal Nazik
Faisal Nazik

Reputation: 2893

Django 401 (Unauthorized) On making PUT request with axios. But working with Postman

I'm trying to update the User in Django from react side. The same function has worked on testing through Postman. But when I try to make a request using Axios in react.js Django doesn't accept it. and throw 401 error.

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

On the postman, I'm using Bearer Token for authorization. And the same token I'm passing in 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
    )

EDIT : Related API VIEW:

@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)

Two different responses on Django server: With Postman

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

And with React frontend

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

Can anybody find out why this happening? And how to fix that problem.

EDIT: Note: This problem only happens on PUT or PATCH requests and work with GET requests. I'm still unable to figure out why this is happening. If I use the same token and test my views with Postman they work absolutely fine but not with a react-redux setup.

Upvotes: 0

Views: 991

Answers (1)

Muhammad Ahmed
Muhammad Ahmed

Reputation: 11

You are passing headers as a second argument whereas in put() method, first argument is for url, second is for data/payload to be sent and the third is for headers. Use like this axios.put(‘url’, data, { headers});

Upvotes: 1

Related Questions