Reputation: 398
I have a node.js API server(e.g. http://host:9002) that needs to set cookies in client, while I have two version of clients, a jQuery one and an AngularJS one. Both client runs at e.g. http://host:8001 behind a nginx as static files.
The question is the exactly same API server returns the exactly same response with set-cookie
head, but in jQuery client, the cookie is simply not be set while in AngularJS client, everything is fine. This is what I mean 'half' working and made me really frustrated.
I've tried chrome and safari, the same result.
In AngularJS client, I use $resource
to send request and In jQuery is '$.ajax'.
The set-cookie in response head is the following one(inspected by chrome):
connect.sid=<some session id here>; Path=/; HttpOnly
What i have tried is to move the jQuery client also serves at http://host:9002, and this makes the set-cookie head works. To me, it looks like that i'm violating Same Origin Policy. But why angularJS client is working though?
================= UPDATE:
for example, the account/login
API:
In AngularJS:
m.factory('accountlogin', ($resource)->
$resource(UrlServer+'/account/login',{},{
login: {method:'PUT', params:{}, isArray:false}
})
)
and using as:
accountlogin.login({
username: u,
password: p,
}, function(r) {
//some callback here;
});
While in jQuery:
sys{
req:function(url, type, data,callback){
var path = sys.SERVER_BASE;
$.ajax({
type : type,
url : path + url,
dataType : "json",
data:data,
success : function(data){
if(callback)callback(data)
},
error:function(data){
if(callback)callback(data)
console.log('fail');
}
});
}
}
using as:
var _data = {
username:$('.loginName').find('input').val(),
password:$('.loginPassword').find('input').val(),
}
sys.req("account/login", 'PUT', _data, function(data){
if(data.status == 'success'){
// some success callback
}else if(data.status == 'failed'){
// some failed callback
}else sys.output('Login failed');
})
Upvotes: 0
Views: 308
Reputation: 398
Since I have Access-Control-Allow-Credentials: true
in Response header, I add xhrFields: { withCredentials: true }
in $.ajax, and the cookies finally could be set.
Source code as following:
req:function(url, type, data,callback){
var path = sys.SERVER_BASE;
$.ajax({
type : type,
url : path + url,
dataType : "json",
data:data,
xhrFields: { withCredentials: true },
success : function(data){
if(callback)callback(data)
},
error:function(data){
if(callback)callback(data)
console.log('fail');
}
});
},
Upvotes: 1