预检请求不允许重定向

Fra*_*lde 6 django apache2 cors reactjs django-cors-headers

我有一个问题,尝试使用rest api时会收到响应:“ 从原始地址“ https://kollektivet.app ” 获取到' https://kollektivet.app:8082/api/login/ '的访问权限已被CORS政策阻止:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。”

尝试获取时的响应图片

当我尝试使用任何其他api时,就会发生这种情况。从我所阅读的内容来看,此错误表示我正在尝试重定向,但不是。

后端是Django,看起来像这样:

    @csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def register(request,):
        password = request.data.get("password", "")
        email = request.data.get("email", "")
        if not email and not password and not email:
            return Response(
                data={
                    "message": "username, password and email is required to register a user"
                },
                status=status.HTTP_400_BAD_REQUEST
            )
        new_user = User.objects.create_user(
            email=email, password=password
        )
        return Response(status=status.HTTP_201_CREATED)
Run Code Online (Sandbox Code Playgroud)

前端处于反应状态,如下所示:

createUser(event) {
        event.preventDefault();

        let data = {
            name: this.state.name,
            password: this.state.password,
            repeatPassword: this.state.repeatPassword,
            email: this.state.email
        };

        if (this.state.name !== '' && this.state.password !== '' && this.state.email !== '' && this.checkPasswords()) {
            console.log('name', this.state.name, 'password ', this.state.password, 'email ', this.state.email);
                fetch("https://kollektivet.app:8082/api/register/", {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                    },
                    mode: "cors",
                    body: JSON.stringify(data)
                })
                    .then(response => response.json())
                    .then(data => console.log(data))
                    .catch(error => console.log(error));
            this.setState({message: "Du er nå registrert! For å aktivere din konto trykk på linken som vi har sendt til deg på epost"});
            this.setState({name: ""});
            this.setState({password: ""});
            this.setState({repeatPassword: ""});
            this.setState({email: ""});

        }
    }
Run Code Online (Sandbox Code Playgroud)

我确实有这是Django设置文件:

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)
Run Code Online (Sandbox Code Playgroud)

如果相关的话,我正在apache2上运行它。端口8082也关闭。当它在同一服务器上时,是否需要将其打开?

谢谢!

ric*_*ier 4

您将被重定向到site.site.comapi/register/

你有其他中间件可以做到这一点吗?也许在 Apache 配置中?

注意这是301,因此您的浏览器已缓存此响应,并且现在将始终重定向到那里,即使您浏览了导致此重定向的代码,或者即使您停止了 Django 运行。

因此,您还需要清除浏览器中的重定向缓存。

这就是我不喜欢301回复的原因。302更有礼貌。