在从浏览器(使用axios的reactjs)到Django服务器的请求中删除授权令牌,从而获得401(未经授权的),但同样的请求与邮递员工作得很好。请求的代码
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设置不是问题。
发布于 2020-05-15 04:15:32
将选项/config作为第三个参数传递给axios.put。第二个参数是数据/有效载荷。
像这样的
axios.put('http://localhost:8000/user-registration/', {}, config).then(
res => {
console.log(res.status)
}
)https://stackoverflow.com/questions/61811629
复制相似问题