Unable to read cookie header with Angular - angularjs

I'm stacking on a shit problem and can't find a solution... maybe has someone an idea.
I have a rest api based on sails.js and send a post request via Angular.js - works fine I get all response data!
But im unable to read the header cookie. The cookie is always null...
In the header should be a 'Set-Cookie'. If I call the same function with a Rest tool I get the cookie header.
I'm working local host port :8000. The rest api is on port :1337
$http.post(url, json)
.success(function(data, status, headers, config) {
console.log(headers('Server'));
console.log(headers('Set-Cookie'));
})
.error(function(data, status, headers, config) {
console.log("error");
console.log("status " +status);
console.log("status " +angular.toJson(data));
});
Any idea?
Cheers!!

First of all, you should never need to get the set-cookie header in Javascript; the browser handles setting the cookie for you. If you want to check if the cookie was part of the response, it's better to use your browser's development console.
More to the point, the issue here is that the cookie is not going to be set at all since this is a cross-origin AJAX request (different ports counts as a different origin) and you probably haven't set the CORS settings in Sails to allow the request through.
The full documentation for CORS in Sails is here. The easiest way to get started with testing it is to open your /config/cors.js file and set allRoutes to true; this will allow all CORS requests to go through unimpeded, regardless of their origin or the route they're trying to access. Once you've got that working, you can use the more fine-grained settings to lock down access if you want.
Note that by default, only a very few response headers from a cross-origin request will be made available via Javascript, of which set-cookie is definitely not one!

Related

CORS headers are not exposed in react/axios even if the headers are listed in Access-Control-Expose-Headers in response from server

I have a react app which uses Axios for requesting server. My server is a grails app.
I want to read all response headers in my client site react code. For this in my grails app, i have set to expose all the headers i need and they are showing in browser and also listed in Access-Control-Expose-Headers. But still i am not able to access the header in my code.
In my axios code, i am using axios interceptor to read the response like :
api.interceptors.response.use(function (response) {
console.log("response",response)
let reqObject = response.request
console.log("type", typeof reqObject)
let resHeaders = reqObject.getResponseHeader('prabin');
console.log("resHeaders",resHeaders)
return response;
},function(error){
return Promise.reject(error);
});
This is giving error in browser console for chrome as :
Refused to get unsafe header "prabin"
I am not understanding what i am missing.
Server needs to give access to your origin. If you see headers in network it doesn't mean that all of this headers you will see in code. Check what you have on server
I found out what was wrong with my implementation. These headers in
Access-Control-Expose-Headers:
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp
It seems they are invalid because of which client javascript code couldn't read the required headers.
After removal of these headers, i am able to read the exposed headers in client code.

Angular JS. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response

I have tried all things, use CORS plugin. disable web-security in chrome.
The response is coming in POSTMAN but not able to fetch it in $http.
$http({
url: "https://interview-api-staging.bytemark.co/books",
method: 'GET',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET,OPTIONS,PUT,DELETE',
'Access-Control-Allow-Headers': 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since'
}
}).then(function(d) {
console.log(d);
});
Client has nothing to do with it. With a CORS header, you're telling the client which other servers do I trust. Those then can share your resources and client won't mind.
For example if you have two domains you tell the client so let your resources be used by your second website, you don't say I trust you as a client.
So you're protecting the server, not client. You don't want AJAX API Endpoints to be accessible by scripts hosted anywhere in the world.
A client has nothing to gain/lose from this. It's only a protection for servers because using AJAX all the URLs are clearly visible to anyone and had it been not for this protection, anybody could go-ahead run their front end using your API, only servers have to lose from this so they get to decide who can use their resources.
source.
As mentioned you don't need to do any cors related stuff in the front-end. Make sure the cors headers are sent from the backend in its response headers.
It is the server that has to protect itself so they have to tell some rules to the client which client will follow. By default, the client will accept everything.
Use CORS in your backend. Otherwise, you can check out Allow-Control-Allow-Origin: * in the Chrome Web Store, use chrome extension.
when you trying to hit through the angular app you need to turn on that extension.
otherwise you need to active CORS in your backend application

Get a "Response header" Cookie from angular $http POST request

I'm writing a small app using angular.
I need to access a couch database. I only have a user in that DB.
Using cURL commands I can request a session cookie to that database and that use that cookie to request a specific document.
When in angular code I use:
$http.post(url, data).then(...);
Where 'data' has username and password, I can see the cookie using chrome (like in this image chrome dev tool output), but in a code, I can't access it.
Can someone help me with this?
You can not access an HttpOnly cookie using script in browser due to security reasons. It can only be accessed on server.
If you need to include cookies in cross domain requests use withCredentials in the request. See $http docs
$http.post returns a response with a property:
headers – {function([headerName])} – Header getter function.
So you should be able to do something like
.then((response) => {
console.log(response.headers('set-cookie'));
});
See the documentation here
Try to use response.headers('set-cookie')
For the crossdomain situation, the server has to send
Access-Control-Expose-Headers: set-cookie header to make the custom headers visible.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Expose-Headers

Angular, Cannot make an an API call probably because of CORS issue

I am trying to make an Angular application consuming Foreign Exchange (forex) market API.
$http({
method: 'GET',
url: 'http://www.apilayer.net/api/live?access_key=[MY ACCESS KEY]'
}).then(function(response){
console.log(response);
})
I keep getting the following error when I look at the browser console.
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
The weirdest part is that it used to work - I was able to retrieve JSON info from the API call without a problem, but it does not any more.
Is there anyone who can point me to a set of possible causes? Would appreciate it!
If you didn't change anything in your code (say, the path for the api) then it must be one of two thing:
The browser configuration has changed
The api provider has blocked cross domain request, you should contact him, maybe he require callback with jsonp ajax request

AngularJS's $http.post() sends each time two AJAX requests, one without the data and one with

I have a weird problem with AngularJS's $http service which, as far as I can see, no one else has.
Every time I use $http.post() to sent cross domain requests, I can see in the developer tools (network pane) that two different requests are being sent: one, without any data, and immediately after that another one is sent which has all the data and returns with the correct response from the server.
Here's an example:
$http.post(url+'getSiteList.php', {session_id: $scope.session_id(), withCredentials: true})
.success(function(data, status, headers, config) {
console.log(data);
....
Does anyone know what's causing this? I checked the code, and the $http.post method is only being called once.
It's all about how browsers manage CORS. When making a cross-domain request in angular, the browser will automatically make a HTTP OPTIONS request to the specified URL/URI it is called as "pre-flight" request or "promise".
As long as the remote source returns a HTTP status code of 200 and relevant details about what it will accept in the response headers, then the browser will go ahead with the original JavaScript call.

Resources