简体   繁体   中英

Authorization header is stripped down in put request from browser but working fine in Postman

Mine Authorization token in getting stripped down from request from browser(reactjs using axios) to Django server and hence getting 401(unauthorized) but the same request is working fine with the postman. code for the request

const config = {
        headers:{
           'Content-Type': 'application/json',
           'Authorization': `Token ${localStorage.token}`
        }
     }
    console.log(config.headers.Authorization)
    console.log(localStorage.token)

    axios.put('http://localhost:8000/user-registration/', config).then(
         res => {
            console.log(res.status)
         } 
      )
}

Djnago method

class UserRegistrationEvent(APIView):
permission_classes = (IsAuthenticated,) 
authentication_classes = (TokenAuthentication, ) 
def get_object(self, username):
    try:
        return User.objects.get(username = username)
    except MyUser.DoesNotExist:
        raise Http404

def put(self, request, format=None):
    print(request.headers)
    User       = self.get_object(request.user)
    serializer = UserRegistrationEventSerializer(User, data=request.headers)
    if serializer.is_valid():
        serializer.save()
        return Response({'alert': 'registration successful'})
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

as in the method i used print method to find out the headers(for debugging i removed the permission class). CORS setting is not a problem

Pass the options/config as 3rd argument to axios.put . The 2nd argument is data/payload

Like this

axios.put('http://localhost:8000/user-registration/', {}, config).then(
         res => {
            console.log(res.status)
         } 
      )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM