在这个问题上我已经用头撞了几个小时了。我只是无法正确设置 cookie。我设置的 cookie 似乎从未被正确保存或发回。
情况是cookie:
- 发送完全相同的请求时是否会被发回,
- 使用不同路径发送请求时不会被发回。
- 重新启动浏览器后似乎不会持续
- 不会显示在 Chrome 开发者工具的“资源”区域中。
服务器:“Google 应用引擎”上的“webapp”
客户端: Chrome 浏览器、Javascript、jQuery、Ajax 调用
使用以下ajax登录用户,这应该设置一个带有“ token ”的cookie:
$.ajax({
type: 'POST',
url: '/rest/login/',
data: JSON.stringify({username:username, password: password}),
error: function(jqXHR, status, errorThrown){...},
success: function(data, status, jqXHR){...}
});
这会产生以下 header larger pic :
服务器正在 Google 应用引擎上运行 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 :
但似乎没有保存在任何地方,因为我在开发人员工具中探索 cookie 时永远找不到它 larger pic :
当请求路径不完全相同的资源时也不会发送它(“注销”而不是“登录”:
$.ajax({
type: 'POST',
url: '/rest/logout/',
data: JSON.stringify({something:'else'}),
error: function(jqXHR, status, errorThrown){...},
success: function(data, status, jqXHR){...}
});
请求如下所示:
最佳答案
我不确定为什么设置 header 不起作用,也许您可以尝试使用设置 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
方法的源代码:
关于javascript - 从 webapp 设置 cookie。只是行不通,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12223125/