在Django Rest Framework中,当使用Axios Token进行授权时,如果出现401 Unauthorized错误,可以按照以下方式进行解决:
确保在请求头中正确设置了Authorization字段,该字段的值为Bearer Token。
import axios from 'axios';
const token = 'your_token_value';
const headers = {
'Authorization': `Bearer ${token}`
};
axios.get('/api/endpoint/', { headers })
.then(response => {
// 处理响应数据
})
.catch(error => {
// 处理错误
});
在Django的设置文件中,配置REST_FRAMEWORK的DEFAULT_AUTHENTICATION_CLASSES为TokenAuthentication。
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
确保在Django中已经创建了Token对象,并将其与用户关联起来。
# views.py
from rest_framework.authtoken.models import Token
from rest_framework.views import APIView
class ExampleView(APIView):
def post(self, request):
user = request.user
token, created = Token.objects.get_or_create(user=user)
# 其他处理逻辑
确保用户已经登录并且Token有效。
# views.py
from rest_framework.decorators import authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
class ExampleView(APIView):
def get(self, request):
# 其他处理逻辑
如果以上方法仍然无法解决问题,可以进一步检查Token是否正确生成并与用户关联,并确保Token验证类和权限类被正确应用在相关的视图上。