在浏览器的put请求中,授权头被删除了,但在Postman中却能正常工作。

问题描述 投票:0回答:1

我的授权令牌从浏览器(reactjs使用axios)到Django服务器的请求中被剥离,因此得到401(未授权),但同样的请求在postman中却能正常运行。

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方法

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)

如在方法中,我使用print方法找出头文件(为了调试,我删除了权限类)。CORS的设置是没有问题的

django reactjs authorization httprequest
1个回答
0
投票

将optionsconfig作为第三个参数传递给我。axios.put. 第2个参数是datapayload

像这样

axios.put('http://localhost:8000/user-registration/', {}, config).then(
         res => {
            console.log(res.status)
         } 
      )
© www.soinside.com 2019 - 2024. All rights reserved.