Retrieving Cookie from Angular 2 Response

I am in need of assistance as I am struggling to retrieve the cookie from the response. Being new to tsc and ng2, I can't seem to find a solution.

Below is the ng2 http post method:

return this._http
    .post('http://demo...', body, { headers: headers })
    .subscribe(
        (response: Response) => {
            this.storeToken(response);
        }, (err) => {
            console.log('Error: ' + err);
        }
    );

This is the server's response:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With
Set-Cookie: JSESSIONID=A099CC4CA7A25DFBD12701630A7DC24C; Path=/pbcp/; HttpOnly
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 17 Feb 2017 04:08:15 GMT

32
{"status":"OK","message":"User is Authenticated."}
0

I'm puzzled because I can't locate it within the headers array...

Result of console.log(response)

https://i.sstatic.net/hPu2U.png

Result of console.log(response.headers)

https://i.sstatic.net/hPu2U.png

...however, it appears in the cookies section.

https://i.sstatic.net/hPu2U.png

Your help is greatly appreciated!

Answer №1

Upon conducting some research, I managed to identify two issues on my end.

To start with, the cookie was actually set correctly, but I was mistakenly searching for it in the wrong location. All along, I had been looking for it under my localhost:3000 domain, when in fact the cookie was properly stored under the http://demo... domain, which is the expected behavior. I located it by navigating to chrome://settings/ ==> Show advanced settings ==> All cookies and site data... ==> and filtering by the remote host as shown below:

https://i.sstatic.net/11AzK.png


Secondly, I overlooked including withCredentials: true in the remaining request headers as well, which would have allowed for automatic inclusion and acceptance of the cookie.

authenticate(username: string, password: string) {
    var body = `{"username":"${username}","password":"${password}"}`;
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let options = new RequestOptions({ headers: headers, withCredentials: true });

    return this._http
               .post('http://demo...', body, options)
               .subscribe(
                   (response: Response) => {
                       this.doSomething(response);
                   }, (err) => {
                       console.log('Error: ' + err);
                   });
}

I extend my gratitude to @All for their valuable responses and time!

Answer №2

It seems like you are utilizing the angular2 http module to communicate with the server, which will provide an observable containing the server's response.

If you want to access the response, you can subscribe to it:

//...
http.post(...your content...)
 .take(1) // optionally, you can specify a number to take before terminating the subscription 
 .subscribe(response =>{
      console.log(response);
    // It is likely that "response.headers" includes the desired "Set-Cookie"
 });

You can also convert the observable into a Promise:

http.post(...your content...)
  .toPromise()
  .then(response=>{
     console.log(response);
     let headers = response.headers;
     console.log(headers);
  })
  .catch(err=>console.log(err));

In some cases, you may need to use response.json() to retrieve an object from the response.

I hope this explanation helps. If you need more guidance, please provide additional details, and I'll do my best to assist you further.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for incorporating drop-down arrow states into a Bootstrap 4 accordion with Angular or CSS

Is there a simple way to implement an arrow (>) to show the aria-expanded="true" or aria-expanded="false" states in the Bootstrap 4 accordion using either Angular2 or plain CSS? I have gone through several tutorials and attempted numerous methods, but ...

Unnecessary Attributes in Type that Should be Automatically Inherited by Child Component

Within my child component, I am creating the Props interface and incorporating it into the React.Component. These Props must then be passed from the parent component to the child component. So far, everything is clear and logical. However, when I extend ...

An issue has been identified with the NGX-chart timeline not displaying correctly when dynamically loading a component using ComponentPortal in Angular 8

Encounter a timeline display problem when loading ngx charts dynamically in Angular 8 using ComponentPortal. Looking for solutions. Rendering components in a loop like: <ng-template class="custom-area margin-10" [cdkPortalOutlet]="dynamicComponent ...

What is the best approach to inheriting from an Injectable class with multiple Injections in Angular 2?

Could we potentially achieve something similar to this code snippet? I attempted it but didn't have any success: @Injectable() class X { constructor(private http: Http){ // <-- Injection in parent class } method(){ this.http.get()... ...

Taunting a specific occurrence inside a group

Good evening, I am currently in the process of developing tests for the TypeScript class shown below. My goal is to create a test that ensures the postMessage method of the internal BroadcastChannel is called. However, I am facing difficulties in setting ...

Different property 'responseType' types are not compatible

Having trouble making a POST request in Angular 5 that accepts text/plain as a response. The method being called in Angular expects a JSON response, causing an error when trying to parse the response. Attempted to call the method with parameter {responseT ...

What is the best way to clear the parent component's content from the child component in Angular?

Having an issue with Angular routes. The URLs are functioning properly, but when I navigate to the child component, specifically CreateEventComponent, the parent component's content from EventsComponent is also displayed. How can I make sure that th ...

What is the relevance of `type Constructor<T> = Function & { prototype: T }` in relation to Abstract constructor types in TypeScript?

Can anyone help me understand how to use the Abstract constructor types in TypeScript? I came across this question and answer on Stack Overflow regarding the topic: Abstract constructor type in TypeScript The accepted answer provided a one-liner code sni ...

Type aliases using generics may demonstrate varying behaviors from type aliases without generics

Here is a code snippet to consider: type TestTuple = [ { test: "foo" }, { test: "bar"; other: 1; } ]; type Foo<Prop extends string> = TestTuple extends Record<Prop, string>[] ? true : fal ...

Transform a javascript object with class attributes into a simple object while keeping the methods

I am seeking a way to convert an instance of a class into a plain object, while retaining both methods and inherited properties. Here is an example scenario: class Human { height: number; weight: number; constructor() { this.height = 1 ...

What is the best way to instantiate objects, arrays, and object-arrays in an Angular service class?

How can I nest an object within another object and then include it in an array of objects inside an Angular service class? I need to enable two-way binding in my form, so I must pass a variable from the service class to the HTML template. trainer.service. ...

Angular 4 encounters a hiccup when a mistake in the XHR request brings a halt to a

In my Angular 4 application, I have implemented an observable that monitors an input field. When it detects a URL being entered, it triggers a service to make an XHR request. Observable.fromEvent(this._elementRef.nativeElement, 'input') .debou ...

The Ionic mobile application is functioning properly during the development stage, however, it is encountering issues

This is my first experience developing an Ionic app. After finishing it, I noticed that it works perfectly when I run the command ionic serve --open Or when I test it on the Ionic DevApp on my mobile device. However, when I create the .apk file, almost ...

Angular 2 form validation allowing submission to continue despite tag errors

Here is the code snippet provided: <form #theForm="ngForm" novalidate> <div *ngIf="pickUpAddress.cannotVerify"> <div class="form-group"> <sh-manual-address [(ngModel)]="pickUpAddress" #manualAddress="ngModel" [address]="pickU ...

Ways to simulate a service using get() method with a particular data structure

https://i.sstatic.net/zc7bu.pngI've been working on writing unit tests for my component and simulating a service that makes HTTP requests. The response data structure looks like this: { ContactActivityView :[ { Code:"AB", ...

Retrieve the component when there is a change in the variable in Angular versions greater than 4

When invoking the ngx-ebar-treemo component in my main component, I use the following syntax: <ngx-ebar-treemo *ngIf="type=='Bar' && graphic" type1="{{type1}}" type2="{{type2}}"></ngx-ebar-treemo> I need to call this compone ...

Comparing object keys in JavaScript for property values

I'm currently working on comparing the properties of objects by their keys. Here is some example data: const data = [{ "name": "John", "value": "30" }, { "name": "Cindy", "value": "50" }, { "name": "Mathew", "value": "80" }, { ...

Error Message: An issue has occurred with the server. The resolver function is not working properly in conjunction with the next

https://i.stack.imgur.com/9vt70.jpg Encountering an error when trying to access my login page. Using the t3 stack with next auth and here is my [...nextauth].ts file export const authOptions: NextAuthOptions = { // Include user.id on session callbacks ...

Element not recognized: <my-company-form-extra> - have you properly registered this component?

I've been attempting to render a component using the is directive <template> <div> <v-tabs v-model="currentTab" fixed-tabs> <v-tab v-for="(item, i) in tabItems" :key="i">{{ item }} < ...

Angular8 with the [tinymce] library for customizing editor elements and configuring multiline options

I am currently working with Angular 8 and in the template, we have the following code snippet: <editor required class="research-modal__control__input research-modal__control__input__description" formCo ...