0

I am trying to get a header from an http call in AngularJS coming from a PHP website. The admin of the website I am calling assures me that CORS has been enabled and that the server has set a flag to allow js to access cookies. Here is the sample code:

    $http({
        method: "POST",
        url: 'https://example.com/page',
        data: {'Form[foo]': feild1, 'Form[bar]': field2},
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
    }).then(function(data, status, headers, config) {
        console.log(data.data);
        console.log(headers()['Set-Cookie']); 
    }, function(err) {
        console.error('ERR', err);
    })

In the first log comment, I can see the web page returned. In the Chrome Inspector, I can click on the reply for page and see the headers, including 'Set-Cookie'. However, the second log comment returns:

 TypeError: undefined is not a function

I have done a lot of searching for answers and trial and error tests. For example:

  }).then(function(data, status, headers, config) {
        console.log(data.headers);            

Result ->

function (name) {
  if (!headersObj) headersObj =  parseHeaders(headers);

  if (name) {
    return headersObj[lowercase(name)] || null;
  }

  return headersObj;
}   

As well as:

  }).then(function(resp) {
    console.log(resp.headers["Set-Cookie"]); 

Result -> undefined

console.log(resp.header('Set-Cookie')); 

Result -> TypeError: undefined is not a function

console.log(headers());

Result -> TypeError: undefined is not a function

I also tried using angular-cookies (after a Bower install, script tag in the index, inject $cookies and $timeout):

        $timeout(function(){
            console.log($cookies.session)
        });

Result -> undefined

Also

console.log($cookieStore.get('Set-Cookie'));

Result -> undefined.

I have read many questions regarding this issue, but none of the answers proposed have worked. I would be grateful if someone could point me in the right direction.

2 Answers 2

1

From the documentation you should be able to retrieve headers as follows

console.log(headers('Set-Cookie'));
Sign up to request clarification or add additional context in comments.

5 Comments

I have tried that. The list above is not exhaustive, as I have tried many variations searching for the right method. 'console.log(headers('Set-Cookie'));' shows up in the console as: 'TypeError: undefined is not a function'. So what does this say about the problem? Is that error a hint of some underlying situation?
Odd I've just tried it using Plunker and it works as described. plnkr.co/edit/UThkcCHkottOUQ1R8q43?p=preview
Thanks for the link to the Plunker. However, when I click on fetch, the alert says the content is null. I used Chrome and Firefox. What could the issue be?
I was showing that it doesn't give a type error, it retrieves the value which as the header doesn't exist is null.
The header retreived is null??
1

The $http service returns a promise which is resolved with an object that has a field named headers which is a function to get a header.

So to fix your existing code you jest need to change the

.then(function(data, status, headers, config) {
        console.log(data.data);
        console.log(headers()['Set-Cookie']); 
    }, function(err) {
        console.error('ERR', err);
    })

to

.then(function(resolvedObject) {
        console.log(resolvedObject);
        console.log(resolvedObject.headers('Set-Cookie')); 
    }, function(err) {
        console.error('ERR', err);
    })

You mixed it with the success and error functions which are tied to the same promise that returns.

Edit:
Updating the snippet from the question:

$http({
        method: "POST",
        url: 'https://example.com/page',
        data: $.param({'Form[foo]': feild1, 'Form[bar]': field2}),
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
    }).then(function(resolvedOcject) {
        console.log(resolvedOcject);
        console.log(resolvedOcject.headers('Set-Cookie')); 
    }, function(err) {
        console.error('ERR', err);
    });

also, I believe your intention was to use the value of Form[foo] as the parameter name. If so the above code will not give you that, you need to extract it separately (not in this line, but create the params before):

// As an object
var params = {};
params[Form.foo] = 'field1';
params[Form.bar] = 'field2';

// Or as a query string
var queryString = Form.foo + '=' + field1 + '&' + Form.bar + '=' + field2;

7 Comments

That is an interesting answer, but does not give me the Set-Cookie value which I can see in the console network tab. The first log comment shows when appears to be a long mix of the headers and the html response. The second log comment returns 'null'.
I believe it means that there is no 'Set-Cookie' header in the response... I think you have another problem in your request: since you're sending a x-www-form-urlencoded request you need the body to be in the form of name1=value1&name2=value2 and so on... you can use jQuery.param() to turn the JSON into a params string.
How could I use jQuery.param() in this situation? Can you provide an example usage please?
I updated my answer. Of course you'd also have to add jQuery to your page. If you could clarify some more about how you get your parameters, I'll be able to help you build those too
Thanks @idan. The form params are meant to mimic what the php form is doing. I am trying to make a hybrid mobile client that can talk to the existing php site. The admin told me to use 'Form[foo]:asd' explicitly. Since the original post above returns the Set-Cookie in the console Network tab, it seems it is just a problem of how to access that correctly, and not an issue with how the params are being sent. I have included jquery in bower components & in the index page, but the $.param call returns Uncaught SyntaxError: Unexpected token {. Do I have to make aa service or factory?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.