【发布时间】:2026-02-06 22:55:01
【问题描述】:
AngularJS 使用 REST 对服务器端进行身份验证,并获取 JSESSIONID cookie。 在下一步中,我将尝试使用 REST 从服务器端获取一些 JSON 数据以及在上一步中获得的会话 cookie。这是客户端代码:
getSomeJSONDataFromServer:function() {
var deferred = $q.defer();
$http({
method: 'POST',
withCredentials: true,
url: "http://domain.name/app/someURL",
headers:{
'Accept':'application/json',
'Content-Type':'application/json; charset=utf-8',
'Access-Control-Request-Headers': 'X-Requested-With, content-type, accept, origin, withcredentials'
}
})
.success(function(data, status, headers, config) {
// handle data
})
.error(function(data, status, headers, config) {
// handle error
});
return deferred.promise;
}
上面的代码可以正常工作:
当我在上面的 POST 请求正文中发送一些数据时,问题就开始了。
...
$http({
method: 'POST',
withCredentials: true,
url: "http://domain.name/app/someURL",
headers:{
'Accept':'application/json',
'Content-Type':'application/json; charset=utf-8',
'Access-Control-Request-Headers': 'X-Requested-With, content-type, accept, origin, withcredentials'
},
data: '{}'
})
.success(...
上述代码在预光照请求中失败:
看起来服务器启动了一个新会话,因为会话 cookie 由于某种原因没有发送。无论如何,我觉得我错过了一些非常简单的东西,一些标题或类似的东西...... 任何想法表示赞赏。提前致谢。
【问题讨论】:
-
好像是跨域调用的问题。 AJAX 调用仅在您调用的 url 与调用脚本位于同一域时发送 Cookie。
-
是的,绝对是 CORS 调用。它一直有效,直到您将正文添加到请求中...
标签: rest session-cookies cors preflight angularjs-http