I've been working on an AngularJS project which has to send AJAX calls to an restfull webservice. This webservice is on another domain so I had to enable cors on the server. I did this by setting these headers:
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "http://localhost:8000"); cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true"); cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
I'm able to send AJAX requests from AngularJS to the backend but I'm facing a problem when I try to get an attribute of a session. I believe this is because the sessionid cookie doesn't get send to the backend.
I was able to fix this in jQuery by setting withCredentials to true.
$("#login").click(function() { $.ajax({ url: "http://localhost:8080/api/login", data : '{"identifier" : "admin", "password" : "admin"}', contentType : 'application/json', type : 'POST', xhrFields: { withCredentials: true }, success: function(data) { console.log(data); }, error: function(data) { console.log(data); } }) }); $("#check").click(function() { $.ajax({ url: "http://localhost:8080/api/ping", method: "GET", xhrFields: { withCredentials: true }, success: function(data) { console.log(data); } }) });
The problem that I'm facing is that I can't get this to work in AngularJS with the $http service. I tried it like this:
$http.post("http://localhost:8080/api/login", $scope.credentials, {withCredentials : true}). success(function(data) { $location.path('/'); console.log(data); }). error(function(data, error) { console.log(error); });
Can anyone tell me what I'm doing wrong?
withCredentials property is a boolean value that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates.
$http is an AngularJS service for reading data from remote servers.
The problem is as follows, $http. get is asynchronous, before the response is fetched, the function returns. Therefore the calling function gets the data as empty string.
To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults.
You should pass a configuration object, like so
$http.post(url, {withCredentials: true, ...})
or in older versions:
$http({withCredentials: true, ...}).post(...)
See also your other question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With