Javascript Django REST身份验证无法使用React
实际上我想要:如果用户经过身份验证:然后使用用户创建/获取购物车, 其他:使用会话密钥创建/获取购物车。但首先,身份验证出现了问题 起初,我尝试注册用户并将密钥(从drf获得)保存在本地存储器中 在Reactjs中:Javascript Django REST身份验证无法使用React,javascript,python,reactjs,django,django-rest-framework,Javascript,Python,Reactjs,Django,Django Rest Framework,实际上我想要:如果用户经过身份验证:然后使用用户创建/获取购物车, 其他:使用会话密钥创建/获取购物车。但首先,身份验证出现了问题 起初,我尝试注册用户并将密钥(从drf获得)保存在本地存储器中 在Reactjs中: signupHandler=()=>{ fetch('http://127.0.0.1:8000/api/rest-auth/registration/', { method: 'POST', headers:{
signupHandler=()=>{
fetch('http://127.0.0.1:8000/api/rest-auth/registration/', {
method: 'POST',
headers:{
'content-type':'application/json',
},
body:JSON.stringify({
'username':this.state.username,
'email': this.state.email,
'password1': this.state.pass1,
'password2': this.state.pass2
})
})
.then((response)=>{
response.json().then((result)=>{
if (result.key !== undefined){
localStorage.setItem('login', JSON.stringify({login: true,token:result.key}))
this.setState({registered: true})
}
})
})
}
我想这里没问题。如果我使用console.log()打印键,它将成功打印该键
现在看看我的视图.py。我认为问题就在这里
@api_view(['GET'])
#@permission_classes((IsAuthenticated,))<<< if i comment out this line, and try to call this function, it shows >>>Forbidden: /addToCart/21/
def addToCart(request, pk):
print(request.user)#>>>AnonymousUser
product = get_object_or_404(Product, pk=pk)
if request.user.is_authenticated:
print('authenticated')#>>> nothing prints
mycart, __ = Cart.objects.get_or_create(user=request.user)
mycart.product.add(product)
else:
print('session')#>>>session
if not request.session.exists(request.session.session_key):
request.session.create()
mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key)
mycart.product.add(product)
return Response({'response':'ok'})
所以我的问题是:
*如果我注释掉@permission\u classes((IsAuthenticated,)
这一行,它为什么会显示禁止。因为我也想,用户可以添加项目与会话
*(在views.py中)当我打印request.user
时,它会显示>>>匿名用户。如何打印真实用户
- 最后,我如何使用经过身份验证的用户将项目添加到购物车中
DEFAULT\u AUTHENTICATION\u CLASSES
,或者在api\u视图中添加装饰程序@AUTHENTICATION\u CLASSES([TokenAuthentication])
。由于您需要API也可供未经身份验证的用户访问,因此不需要
@permission\u classes
。未经身份验证的权限类将拒绝任何未经身份验证的用户的权限,否则将允许权限。如果希望API仅可供注册用户访问,则此权限适用。提到@Bubai,先生,但我已通过身份验证,我的密钥存储在本地存储器中。我使用授权令牌调用了该函数。那么,拜托,你能告诉我为什么我还没有通过认证吗?谢谢你,先生。你救了我一天
addToCart=()=>{
var id = this.props.id
let store = JSON.parse(localStorage.getItem('login'))
console.log(store.token);//successfully print the key
var url = 'http://127.0.0.1:8000/addToCart/'+id+'/'
fetch(url,{
method:'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token '+store.token
}
}).then(res=>res.json().then(result=>{
if(result.response === 'ok'){
this.props.dispatch({
type: 'itemInCart',
})
this.setState({addedToCart: true})
}
}))
}