【问题标题】:Setting cookies from webapp. Just won't work从 webapp 设置 cookie。就是行不通
【发布时间】:2012-08-26 17:32:25
【问题描述】:

在这个问题上我已经用头撞了几个小时。我只是无法正确设置 cookie。我设置的 cookie 似乎永远不会被正确保存或发回。

情况是cookie:

  • 发送完全相同的请求时会被退回,
  • 发送具有不同路径的请求时不会被发回。
  • 重新启动浏览器时似乎不存在
  • 不显示在 Chrome 开发者工具的“资源”区域中。

服务器:“谷歌应用引擎”上的“webapp”

客户端: Chrome 浏览器、Javascript、jQuery、Ajax 调用

使用以下 ajax 登录用户,这应该设置一个带有“令牌”的 cookie:

$.ajax({
    type:   'POST',
    url:    '/rest/login/',
    data: JSON.stringify({username:username, password: password}),
    error: function(jqXHR, status, errorThrown){...},
    success: function(data, status, jqXHR){...}
});

这会产生以下标题larger pic

服务器在谷歌应用引擎上运行 webapp,这是它设置 cookie 的方式:

w_self.response.set_status(200)
#     Put the token in the cookies. "str()" is used because without it, there is a unicode error
w_self.response.headers.add_header(str('Set-Cookie'), str('token=%s; max_age=360;' % token))
#     The user
r_object['user'] = the_user
# Respond
w_self.response.out.write(json.dumps(r_object))

如果该页面再次被请求,cookie被发送回服务器larger pic

但似乎没有保存在任何地方,因为我在开发者工具larger pic中探索cookie时永远找不到它@:

在请求路径不完全相同的资源时也不发送它('logout'而不是'login':

$.ajax({
    type:   'POST',
    url:    '/rest/logout/',
    data: JSON.stringify({something:'else'}),
    error: function(jqXHR, status, errorThrown){...},
    success: function(data, status, jqXHR){...}
});

这是请求的样子:

larger pic:

【问题讨论】:

    标签: javascript ajax google-app-engine web-applications cookies


    【解决方案1】:

    我不确定为什么设置标题不起作用,也许你可以尝试使用 set cookie 方法:

    # Saves a cookie in the client.
    response.set_cookie('some_key', 'value', max_age=360, path='/',
                        domain='example.org', secure=True)
    

    http://webapp-improved.appspot.com/guide/response.html#setting-cookies

    这里是set_cookie 方法的来源:

    http://code.google.com/p/googleappengine/source/browse/trunk/python/lib/webob_1_1_1/webob/response.py#616

    【讨论】:

      【解决方案2】:

      如果您未设置路径,则默认设置是仅将其发送回设置路径的路径,如您所见。

      我也认为它也意味着 Max-Age 而不是你所拥有的 max_age,但不管 webapp2 给你的响应对象有一个 set_cookie method 虽然 - 我相信这一切都会正确地完成。

      【讨论】:

        猜你喜欢
        • 2015-10-23
        • 1970-01-01
        • 2012-07-21
        • 1970-01-01
        • 2018-06-05
        • 1970-01-01
        • 1970-01-01
        • 2011-08-25
        • 2013-12-29
        相关资源
        最近更新 更多