我的前端在 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 没有设置呢?
最佳答案
感谢@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) {
...
});
关于ajax - 为什么我的cookie没有针对不同端口的跨域请求设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33270491/