授权 header 在来自浏览器的 put 请求中被删除,但在 Postman 中工作正常
Authorization header is stripped down in put request from browser but working fine in Postman
我的授权令牌从浏览器(使用 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)
在我使用打印方法找出 headers 的方法中(为了调试,我删除了权限 class)。 CORS设置没有问题
将 options/config 作为第三个参数传递给 axios.put。第二个参数是 data/payload
像这样
axios.put('http://localhost:8000/user-registration/', {}, config).then(
res => {
console.log(res.status)
}
)
我的授权令牌从浏览器(使用 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)
在我使用打印方法找出 headers 的方法中(为了调试,我删除了权限 class)。 CORS设置没有问题
将 options/config 作为第三个参数传递给 axios.put。第二个参数是 data/payload
像这样
axios.put('http://localhost:8000/user-registration/', {}, config).then(
res => {
console.log(res.status)
}
)