简体   繁体   English

无法使用 Javascript 将 cookie 路径设置为根目录

[英]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 答案的解决方案):

  • visiting 127.0.0.1 - didn't work (port is always 80).访问 127.0.0.1 - 不起作用(端口始终为 80)。
  • Uploading to a web server.上传到 web 服务器。 Same result as above.结果与上述相同。
  • visiting the localhost ( localhost and 127.0.0.1 ) on Chrome.访问 Chrome 上的本地主机( localhost127.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM