The headers in the Angular HttpClient Response Object do not show up in the network tab of browsers or when using PostMan

Here is the function that makes a POST call to the server:

 submitData(credential){
    credential = JSON.stringify(credential);    
    return this._http.post("http://localhost:8080/login",credential,{observe: 'response'});
  }

In this section, I am logging the data in the console:

this.jwtService.submitData(data)
    .subscribe((data)=>{
      console.log(data);

    })

Below is the response I receive in the console:

HttpResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/login", ok: true, …}
  headers: HttpHeaders
    normalizedNames: Map(0)
      [[Entries]]
        No properties
      size: 0

When checking my browser's Network tab, I can see the Authorization header with its value:

Request URL: http://localhost:8080/login
Request Method: POST
Status Code: 200 
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade

Response Headers:
Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Expose-Headers: Authorization
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJuYWNodSIsImV4cCI6MTU4NDg2MTYxOH0.Bh46Bv4YWou5kzNp2ib_14Xnu9Ob7G41QqY4_t6UzxdJiq-CHX1yk7BWBmHlOXygMuS7YNVNu0HkhnREoY69iQ
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Length: 0
Date: Sun, 22 Mar 2020 06:20:18 GMT
Expires: 0
Keep-Alive: timeout=60
Pragma: no-cache
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

I also replicated the same response using Postman application.

I am currently seeking a workaround for this issue.

Answer №1

I have discovered the solution to my own query and I want to share it in the hopes that it will benefit someone else.

After making some tweaks to my code,

First, we need to import the tap operator from 'rxjs/operators' as shown below:

import {tap} from 'rxjs/operators'

Next, use the pipe operator as demonstrated below to retrieve the desired header:

 submitData(credential){
    credential = JSON.stringify(credential);    
    return this._http.post("http://localhost:8080/login",credential,{observe: 'response'})
    .pipe(tap(res=>{
        console.log('response',res.headers.get('Authorization'));

    }))
  }

Ensure that your server-side setup includes all necessary CORS configurations and that you are exposing the required headers. For instance, if you require the Authorization header, make sure to include the following on your server-side (assuming the use of spring-boot):

public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .exposedHeaders("Authorization")
                .allowedOrigins("http://localhost:4200");
        WebMvcConfigurer.super.addCorsMappings(registry);
    }

:) Happy Coding

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

What are the common issues with Angular 2's ng-if directive?

I am completely new to working with Angular and have already gone through all the ng-if related questions without finding a solution that fits my issue. Here is my code: <tr *ngFor="#position of positions"> <td> ...

Is the return type of 'void' being overlooked in TypeScript - a solution to avoid unresolved promises?

When working in TypeScript 3.9.7, the compiler is not concerned with the following code: const someFn: () => void = () => 123; After stumbling upon this answer, it became apparent that this behavior is intentional. The rationale behind it makes sens ...

When using Angular, sensitive login credentials are easily visible in the browser's address bar

In my Angular 9 application, I occasionally encounter a rare issue where my authentication data is exposed in the browser address bar. Instead of the expected URL like: http://localhost:8080/#/application/48 it somehow ends up looking like this: http://lo ...

Converting a JavaScript function to TypeScript with class-like variables inside: a step-by-step guide

During the process of converting a codebase to TypeScript, I encountered something unfamiliar. In particular, there are two functions with what appear to be class-like variables within them. The following function is one that caught my attention: const wai ...

HttpClient service not available

Upon transitioning from angular 4.4 to 5.0 and updating all HttpModule to HttpClientModule, an error started to occur. Despite re-adding HttpModule to rule out any dependency issues, the error persisted. My app.module is correctly configured as follows: ...

determine the appropriate month for the calendar month component based on the route selected

I have developed a calendar component where I want to preselect the default month based on the route parameters received for the component. Here is the calendar: <p-calendar [maxDate]="dateTime" [(ngModel)]="selectedMonth" name=&quo ...

"Error: The dist directory is missing in the Angular Docker File

I am in the process of Dockerizing an Angular project and here is my Dockerfile: # 1. Building the Angular app using Node.js FROM node:12 as builder WORKDIR /app COPY package.json package-lock.json ./ ENV CI=1 RUN npm ci COPY . . RUN npm run build-web -- ...

Unlocking the potential: passing designated text values with Javascript

In my current React code, I am retrieving the value from cookies like this: initialTrafficSource: Cookies.get("initialTrafficSource") || null, Mapping for API const body = {Source: formValue.initialTrafficSource} Desired Output: utmcsr=(direct)|utmcmd=(n ...

Using TypeScript generics to constrain to either a number or a string

I am working on coding a react input component that accepts a defaultValue parameter of type string | number. This component has a state type matching the type of the received defaultValue; This is my code: type TypeName<T> = T extends number ? "nu ...

Making Angular Material compatible with Webpack and TypeScript

I am facing a challenge with my angular-typescript project managed by webpack. The issue arises when I attempt to integrate the angular-material library, and I am encountering significant difficulties. Currently, the html portion of my code appears as fol ...

When you use npm uninstall, it deletes the package from package.json, but it does not remove it from the node_modules directory

After attempting to uninstall a package using npm uninstall (package_name) -s The package was successfully removed from package.json but remained in the node_modules folder. How can I effectively remove these unused packages from the node_modules folder? ...

Utilize a web service within a service file and leverage it across multiple locations

I am seeking help with reusing a service function in different parts of my app, specifically to display a certain parameter ('title') in the HTML template. Firstly, I created a service: import { Injectable } from '@angular/core'; impo ...

Disabling the Parent Component Form Submit button until the child component fields are deemed valid

I'm currently utilizing a Template Driven Form. HTML of the Parent Component <form #BasicForm="ngForm" (ngSubmit)="onBasicDetailsSubmit()" id="BasicForm"> <app-input-text [(sharedVar)]="dashboardDetails.Text1" [isMandatory]="true" >&l ...

Ways to avoid using a specific type in TypeScript

Imagine having a class that wraps around a value like this: class Data<T> { constructor(public val: T){} set(newVal: T) { this.val = newVal; } } const a = new Data('hello'); a.set('world'); // typeof a --> Primitiv ...

Structural directive fails to trigger event emission to parent component

Following up on the question posed here: Emit event from Directive to Parent element: Angular2 It appears that when a structural directive emits an event, the parent component does not receive it. @Directive({ selector: '[appWidget]' }) export ...

Execute the function once Router.navigate is completed

Is there a way to execute a specific function after a user successfully logs in, regardless of which page they logged in from? The goal is to redirect the user back to their previous browsing page upon login. I've been using Router.navigate for URL r ...

Create a MySQL JSON_EXTRACT condition using a user-defined search parameter

In a unique and interesting scenario, users are able to store their own JSON objects for records. This is due to the fact that each user has customized objects and data structures that are integral to their normal record. I am looking to enable users to s ...

Tips for transforming a JSON Array of Objects into an Observable Array within an Angular framework

I'm working with Angular and calling a REST API that returns data in JSON Array of Objects like the example shown in this image: https://i.stack.imgur.com/Rz19k.png However, I'm having trouble converting it to my model class array. Can you provi ...

Do Angular pipe promises have the potential to disrupt an application's functionality?

Within my small library, I have implemented a translation pipe that functions perfectly when using Observables. The relevant code snippet can be found here: this.localizationChanges.subscribe(() => { this.fluentService .translationObservable ...

Adjusting the ng-bootstrap carousel to fit within a div inside an ng-bootstrap modal

I have been struggling to correctly adjust the CSS properties in order to make a ng-bootstrap carousel image fit into a specific space (div) within a custom ng-bootstrap modal. Take a look at this modified StackBlitz code. In the provided example, the ima ...