javascript - 可以设置跨域但无法获取值

标签 javascript java cookies

我有一个服务,可以设置 cookie 以禁用页面中的弹出窗口。我已经为此 cookie 设置了一个域,它应该可供该域使用。但是,当我从子域调用该页面时,java 没有获取 cookie 值,而是仍然显示弹出窗口。

即。

http://www.example.com/landing
landing page (cookie is empty - popup was shown) -> calls java backend to set cookie (pop-up)

cookie - {name: 'pop' value: 'n' }
domain - example.com

http://www.abc.example.com/
page with subdomain (I can see the cookie) 
cookie - {name: 'pop' value: 'n' }
domain - example.com

-> make ajax call from http://www.abc.example.com/ to http://www.example.com/landing
cookie - {name: 'pop' value: 'n' }
domain - example.com

现在,当我尝试降落在 http://www.example.com/landing 上时我看到弹出窗口仍在显示。 即使 cookie 被设置为“n”,从日志中我看到从 cookie 读取的值是空的。为什么会出现这种情况?

Java 后端 -

    @RequestMapping(value = "/landing", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Object getPopup(@RequestBody PopRequest req, HttpServletRequest request,
            HttpServletResponse response) {
    ....
     String popup = getCookie(request, "pop");
     // this popup is null
    ... 


}
    public String getCookie(HttpServletRequest request, String name) {
        String value = "";
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equalsIgnoreCase(name)) {
                    jwt = cookie.getValue();
                }
            }
        }
        return value;
    }

请注意,我可以从浏览器看到 cookie,但是当进行调用时,我看到 getCookie 中的 cookie 为 null。

最佳答案

在后端代码中,我可以看到您正在将值初始化为空字符串,并将 cookie 值分配给 jwt 变量。所以,最终reponse(value)返回null。

public String getCookie(HttpServletRequest request, String name) {
        String value = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equalsIgnoreCase(name)) {
                    value = cookie.getValue();
                }
            }
        }
        return value;
    }

关于javascript - 可以设置跨域但无法获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59617962/

相关文章:

javascript - 如何不提交水印文字?

javascript - 如何替换Javascript中的所有字符串?特别是特殊字符的组合

java - 检查圆是否完全包含圆

java - 未定义名为 'transactionInterceptor' 的 bean

cookies - 在 Google Analytics 中禁用 Cookie - gtag.js

javascript - 如果与 GeoJSON 层一起使用, map 标签的 zIndex 无效

javascript - AngularJS ng-repeat 和controllerAs

c# - Ksoap2 : Calling DateTime datatype on . NET Web 服务

javascript - Cookies 或 localstorage 是最好的方法?

javascript - 表达 cookieParser() 困惑