繁体   English   中英

启用权限时前面返回错误 django rest

[英]return error in front when permissions enable 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

这适用于 postman,但是当我尝试对 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控制台给401 unutorized

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不会发送 cookies,除非您设置凭据:'same-origin'。

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 使用了错误的身份验证设置?

我设法解决了这个问题。 这个项目不是我开发的,我不太明白为什么会这样。 我添加到我的许可

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM