I'm having trouble figuring out how to access response headers with HttpClient in Angular 5. Can anyone

I recently developed an authentication service in Angular 5, where I utilize the HttpClient class to make a POST request to my backend server. The backend server then responds with a JWT bearer token.

Here is a snippet of how my request looks:

return this.http.post('http://127.0.0.1:8080/api/v1/login', {
  'username': username,
  'password': password
}, {
  headers: new HttpHeaders()
    .set('Content-Type', 'application/json')
})
  .toPromise()
  .then(response => {
    console.log(response);
    return response;
  });

}

I am having trouble accessing the authorization header from the response object. When I log the response to the console as shown above, it displays 'null'. Interestingly, I have verified that the backend is indeed sending the bearer token by examining the network traffic.

If anyone has any insights or suggestions on how to resolve this issue, please share. Your assistance would be greatly appreciated.

Answer №1

If you want to retrieve the entire response (not just the body), make sure to include the observe: 'response' parameter in your http request. This will allow you to access the headers using res.headers

return this.http.post('http://localhost:3000/api/v1/login', {
        'username': username,
        'password': password
    }, {
        headers: new HttpHeaders()
            .set('Content-Type', 'application/json'),
        observe: 'response'
    })
    .map(res => {
        let customHeader = res.headers.get('custom-header');
    });

Official Documentation

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

Can one access non-static methods within React Navigation's navigationOptions?

Within my form, I am trying to position a submit button to the right of the header that triggers the same method as the submit button located at the bottom of the form. React Navigation necessitates the declaration of a static method named navigationOptio ...

TSLint HTML Report Summary

Currently working on generating an HTML report for the "TSLint" task. Successfully created a report for "JSHint" using a specific package after installation. Struggling to locate a similar reporter for TSLint. "npm install gulp-jshint-html-reporter --sav" ...

Express.js and gridfs-stream are unable to retrieve the error

Imagine an effortless image download server where Express.js takes the request, fetches an image from MongoDB GridFS, and serves it as a response. Everything works fine when the request is valid and the file exists. The issue arises when it fails to catc ...

A guide to simulating components using providers in Angular 4 - Achieving successful unit testing

I am struggling with mocking a component that uses providers in Angular 4. Below is the code snippet I am working on: import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; i ...

What is the concept of NonNullable in typescript and how can it be understood

In TypeScript, the concept of NonNullable is defined as type NonNullable<T> = T extends null | undefined ? never : T For instance, type ExampleType = NonNullable<string | number | undefined>; Once evaluated, ExampleType simplifies to type Exa ...

Generating instances of classes using variables in Typescript

Are there methods to modify the below piece of code in order for it to be compatible with Typescript? public shops: string[] = [ "AShop", "BShop", "CShop", ]; this.shops.forEach((shop, index) => { let instance = new window[shop](index ...

"Encountering an error in Vue.js when trying to dynamically access nested arrays: push function not

My goal is to have two buttons displayed when a user uploads data: one for old products and one for new products. When the user clicks on either button, the corresponding products will be uploaded as 'old_product' or 'new_product'. Howe ...

Send the user to an Angular route once they have successfully authenticated with Google

I'm facing an issue with redirecting users to an Angular route. Here's the scenario: When I'm on the login page and click on Google login, I get redirected to Google for authentication. After successfully logging in, I want to be redirecte ...

Utilize an AngularJS controller to verify the presence of a cookie and display a modal pop-up

In the process of developing a Single Page Application (SPA), I have encountered an issue with an HTML element calling an AngularJS controller. Here is what I need: I want the controller to check for a specific cookie: - If the cookie exists, call a ...

Is it possible to utilize jQuery for dynamically generating a file along with its content?

Here is the HTML snippet I am working on: <ul> <li> Download <a href="#">file1</a> </li> <li> Download <a href="#">file2</a> </li> <li> Download <a href="#">file3</a> </li> ...

Text box content does not refresh unless the page is reloaded

My text box (tbAdresse) is initially empty. I'm using the following JavaScript code to set its value: origin = document.getElementById("tbAdresse").value; if (origin == "") origin = <%=this.GetFormatStringCoordonnees("Paris")% ...

What are the reasons behind my item not triggering an alert even after I have created it, saved it, and attempted to alert it?

I am currently working on a code that allows users to input information which is then stored in an object. However, despite my efforts, when I attempt to retrieve the saved object by alerting one of its values, it indicates that the object does not exist. ...

The Express application appears to be unresponsive, but the data has been successfully saved to the MongoDB database. An error with the

Currently, I am delving deeper into the MERN stack and working on a straightforward CRUD application utilizing it. One of the recent additions to the app includes validators implemented through express-validator for handling requests. However, an issue ari ...

Are you struggling to get basic HTML and JS code to function properly?

I'm currently working on developing a racing game, and my initial step was to create the car and implement movement functionality. However, I've encountered an issue where nothing is displaying on the canvas - neither the rectangle nor the car it ...

What is the reason why the [active] attribute does not function properly in <a mat-tab-link> in Angular?

<div class="d-flex d-column themed-tab-nav"> <nav mat-tab-nav-bar color="primary" [tabPanel]="tabPanel" mat-stretch-tabs="false" mat-align-tabs="start"> <a mat-tab-l ...

A guide on utilizing the React Suite range slider in rsuite

Hello there, I recently started working with the UI framework rsuite (React suite) and everything was going smoothly until I tried to use the Range slider component's API. Unfortunately, I am facing some issues with the labels and tooltips not display ...

The function `find()` will not provide any data, it will only output `undefined`

I am trying to extract the `s_id` field from this JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "s_id": "11E8C70C8A5D78888E6EFA163EBBBC1D", "s_serial": " ...

Is it possible to trigger the setState() function of a parent component when a child component is clicked?

Hey there, I'm a new developer diving into the world of Reactjs. I've been working on setting up a Todo app but struggling to configure it just right. My main challenge is getting a button to add items to the list when submitted. I think I'm ...

Typescript has a knack for uncovering non-existent errors

When I attempted to perform a save operation in MongoDB using Mongoose, the code I initially tried was not functioning as expected. Upon conducting a search online, I came across a solution that worked successfully; however, TypeScript continued to flag an ...

Is there a way for me to attach a link to a picture displayed in a lightbox that directs to an external ".html" file?

I have a platform where users can view images in a gallery and when they click on an image, it opens up in a lightbox. I am trying to add a feature where the opened image can be clicked again to redirect the user to an external page. I attempted to nest t ...