[英]Cannot set cookie path to the root directory with Javascript
On localhost.在本地主机上。 Using Firefox 88.0 (Private window).
使用 Firefox 88.0(私人窗口)。 My document tree:
我的文档树:
/index.html
/page1/index.php
/page2/index.php
Here's my JS to set cookies (on page1
):这是我设置
page1
的 JS(在第 1 页):
function setCookie(name, value) {
document.cookie = name + "=" + value;
document.cookie = "path=/";
}
Which (I think) overwrites the cookie path to /
every time I call the function.每次我调用 function 时,哪个(我认为)会覆盖
/
的 cookie 路径。 At the beginning of the same JS file I have: alert(document.cookie);
在同一个 JS 文件的开头我有:
alert(document.cookie);
. . It displays the full cookie as I save it, including
path=/
.当我保存它时,它会显示完整的 cookie,包括
path=/
。
On the homepage ( /index.html
) I have: <script>alert(document.cookie);</script>
.在主页上(
/index.html
)我有: <script>alert(document.cookie);</script>
。 But it displays an empty alert.但它显示一个空警报。 I don't see the cookies.
我没有看到 cookies。 But if I go back to the
page1
then I see the cookies again.但是如果我 go 回到第
page1
,那么我会再次看到 cookies。 Why is this?为什么是这样?
I've also tried (solutions from other SO answers):我也尝试过(来自其他 SO 答案的解决方案):
localhost
and 127.0.0.1
) on Chrome.localhost
和127.0.0.1
)。 Couldn't resolve.无法解决。 Could anyone help please?
有人可以帮忙吗? Thank you in advance!
先感谢您!
Apparently I have to set the path at the time of setting the cookie, not using document.cookie
after the cookie has already been set.显然我必须在设置cookie时设置路径,而不是在设置cookie后使用
document.cookie
。
This got the problem fixed:这解决了问题:
function setCookie(name, value) {
document.cookie = name + "=" + value + ";path=/"; //Set the path while setting the Value.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.