当权限启用django rest时,返回错误



我有一个视图permission_classes启用

class ProjectCopyView(APIView):
permission_classes = [IsAuthor]
class IsAuthor(BasePermission):
'''Проверка права на авторство проекта'''
message = "Only the author of the project can share it"
def has_permission(self, request, view):
try:
if Project.objects.get(id=view.kwargs['project_id'], user=request.user):
return True
except:
return False

这在邮差工作,但当我试图重复这个请求的js错误

Access to fetch at 'http://127.0.0.1:8080/api/editor/project/1/copy/' from origin 'null' has been thrown blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Django console给401未授权

async function testSizze(){
const res = await fetch("http://127.0.0.1:8080/api/editor/project/1/copy/", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Token 8fdc5648e07851c9ebe3c05f56b4c2400f2d90b9"
},
body: JSON.stringify({
})
});
const json = await res.json();
console.log(json)
}   

当我禁用permission_classes js的请求工作

fetch不会发送cookie,除非您设置凭据:'同源'。

const res = await fetch("http://127.0.0.1:8080/api/editor/project/1/copy/", {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
"Authorization": "Token 8fdc5648e07851c9ebe3c05f56b4c2400f2d90b9"
},
body: JSON.stringify({
"to_user": "admin@mail.ru",
"permission": ["read"],
"all_users": "False"
})
});

所以也许你使用了错误的django-rest-framework认证设置?

我设法解决了这个问题。这个项目不是我开发的,我也不太明白为什么会这样。I add to my permission

if request.method == 'OPTIONS':
return True

最新更新