为什么我的cookie没有设置为不同端口上的跨域请求

时间:2015-10-21 22:41:34

标签: ajax http cookies cross-domain

我在localhost:9000上运行前端,在localhost:4567上运行后端。

 $.post("http://localhost:4567/login",
                {
                    user: u,
                    password: p,
                    crossDomain: true,
                    xhrFields: { withCredentials: true }
                },
                function (data) {
                    window.location.replace("app.html")
                })
                .fail(function (x) {
                    ...
                });

登录请求成功,服务器返回

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:*
Access-Control-Allow-Origin:http://localhost:9000
Access-Control-Request-Method:*
Cache-Control:no-cache, no-store, must-revalidate
Content-Length:1
Content-Type:text/html; charset=UTF-8
Expires:Thu, 01 Jan 1970 00:00:00 GMT
Server:Jetty(9.0.z-SNAPSHOT)
Set-Cookie:JSESSIONID=1bput5i7fmccb13o5pe2rop8w0;Path=/

然而,浏览器不设置cookie,未来的请求没有此cookie。在Chrome和Firefox上测试过。如果前端和后端或在同一端口,它工作正常。那么,如果我在不同的端口上调用后端,为什么不设置cookie呢?

1 个答案:

答案 0 :(得分:3)

感谢@ Kenney的评论,将$ .post更改为$ .ajax是修复:

$.ajax(
                        {
                            url: "http://localhost:4567/login",
                            method: "post",
                            data: { user: u, password: p },
                            user: u,
                            password: p,
                            crossDomain: true,
                            xhrFields: { withCredentials: true }
                        }).done(function(data) {
                             window.location.replace("app.html");
                        })
                        .fail(function (x) {
                            ...
                        });