我在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呢?
答案 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) {
...
});