首页 > 解决方案 > 在 django 中重定向后无法访问 cookie

问题描述

这是我处理过的情况。我会尽量解释得更容易理解。

我希望用户单击网站中的一个按钮(让我们将此站点命名为 A),该按钮会触发一个 ajax 发布请求到 django 视图。在这个视图中,我必须response.set_cookie使用与 ajax 发布请求一起传递的数据来设置 cookie。

成功响应后,我迅速将页面重定向到不同的网站(假设这个网站是 B)。当页面加载时,我想访问我从站点 A 设置但无法访问的 cookie。

下面是我的代码。

index.html(在站点 A 中,发出 ajax 发布请求的位置)

<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <button onclick=setCookies()>Create Invoice</button>
</body>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script type="text/javascript">
    const setCookies = () => {

        ...some codes...

        const xhr = new XMLHttpRequest()

        const data = {
            'HTTP_LOGIN_TYPE': 'admin',
        }

        $.ajax(
            {
                type: 'POST',
                url: url, // hits endpoint where sets cookies.
                crossDomain: true,
                data: data,
                success: () => {
                    window.location.href = to site B
                },
                error: xhr => {
                    console.log(xhr.responseText)
                }
            }
        )
    }
</script>

</html>

views.py(在站点 B 中,设置 cookie)

from django.http import HttpResponse
from django.conf import settings
from rest_framework.views import APIView

class AuthenticateUser(APIView):

    def post(self, request):

        data = request.POST
        login_type = data['HTTP_LOGIN_TYPE']

        if login_type == 'admin':
            response = HttpResponse(
                'Setting login_type to %s' % login_type)
            response.set_cookie(
                'login_type', login_type, max_age=604800, domain=settings.SESSION_COOKIE_DOMAIN)

            return response

views.py(在站点 B 中,从 index.html 中的 ajax 调用重定向,我想在其中访问 c​​ookie)

import re
from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.views import APIView


class GetInvoice(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'student/base.html'

    def get(self, request, student_id):

        login_type = 'hello'

        if 'login_type' in request.COOKIES:
            login_type = request.COOKIES['login_type'] # Can't access cookies

       ... more code ...

仅供参考,url虽然index.html站点 A 和站点 B 的域不同,但站点 B 的域是相同的。

我不确定我错过了什么。过去几天我一直在搜索文章、帖子等,并根据它们进行了尝试,但没有运气。

如果我错过了什么,请纠正我。

提前致谢。

标签: pythondjangoajaxcookies

解决方案


由于同源策略,您无法访问不同域的 cookie。

对存储在浏览器中的数据(例如 localStorage 和 IndexedDB)的访问按来源分开。每个源都有自己独立的存储,一个源中的 JavaScript 无法读取或写入属于另一个源的存储。

但是,如果域 B 是 A 的子域,它将自动查看域 A 的 cookie。如果您无法更改域,则应使用请求标头/正文中的 cookie 重定向到站点 B。


推荐阅读