Is Angular 4 failing to set headers properly or is Express.js searching in the wrong place?

When interacting with an Express.js API, I encountered a issue regarding the handling of auth tokens. The problem arose when sending the token in the request headers using Angular 4 compared to Postman. In Postman, setting the header named 'Authorization' worked perfectly. However, when trying to send it with Angular 4 like this:

const headers = new HttpHeaders()
  .set('Content-Type', 'application/json')
  .set('Authorization', `${token}`);
this.http.get<Response>(`${this.apiURL}dashboard/`, { headers: headers })
  .subscribe(res => console.log(res));

Upon logging the headers object, everything appeared to be correctly set. But attempting to retrieve the token in my express route using:

const token = req.get('Authorization');

always resulted in 'undefined'. It raised the question: What is angular doing differently from postman? https://i.stack.imgur.com/SorQA.png

Here is the logged result when trying to extract the token: https://i.stack.imgur.com/9PriP.png

Postman continues to work flawlessly: https://i.stack.imgur.com/BR0Vf.png

https://i.stack.imgur.com/X09IE.png

Answer №1

HttpHeaders can't be changed once they're created. More information can be found at https://angular.io/api/common/http/HttpHeaders To set headers, follow this example:

let headers = new HttpHeaders();
headers = headers.set('Authorization', 'token');

Answer №2

Here is a guide on how to set headers for different Angular versions:
For Angular versions prior to 5

        import { Http, Headers, RequestOptions } from "@angular/http";

        // inside your Class
        headers = new Headers({
                "Content-Type": "application/json",
                "Accept": "q=0.8;application/json;q=0.9",
                "Authorization": "token"
        });
        options = new RequestOptions({ headers: this.headers });

Make sure to include `this.options` in your http request.

For Angular version 5 and above

import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

Now when making an http request, remember to pass along `httpOptions`.

Answer №3

After some investigation, I discovered a solution that differs from the instructions in the express.js documentation. Instead of using req.get('Authorization'), using req.headers['Authorization'] proved to be the perfect solution.

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

How can I retrieve the length of an array in vuejs?

This snippet includes a script tag <script> export default { data() { return { blogs: [], }; }, created() { this.paginate_total = this.blogs.length / this.paginate; }, }; </script> Displayed below is the respo ...

Can someone please explain how I can extract and display information from a database in separate text boxes using Angular?

Working with two textboxes named AuthorizeRep1Fname and AuthorizeRep1Lname, I am combining them in typescript before storing them as AuthorizeRep1Name in the database. Refer to the image below for the result. This process is used to register and merge the ...

Guide to populating a full calendar using JSON information

Implementing the FUllCALENDAR CSS template for creating a meeting calendar has been my current project. The servlet class I am using is CalendarController. However, when running it, the output appears as follows: {"events":[{"id":1,"title":"1","s ...

Adjusting the minimum value on a textfield with JQuery Validate plugin in real-time

I am attempting to dynamically update the minimum value on one field based on input from other fields. Here is a brief overview of my code: $("#new_project").on("click", function() { switch($('input:radio[name=quality-level]:checked').val() ...

Navigating through ionic2 with angularjs2 using for-each loops

I developed an application using IONIC-2 Beta version and I am interested in incorporating a for-each loop. Can anyone advise if it is possible to use for each in Angular-V2? Thank you. ...

Is it feasible to link an Angular property value to the value of an HTML data attribute?

Can an Angular property value be bound to a data attribute on a template element? <h1 data-name="{{name}}">Hello from {{ name }}!</h1> Example Link After running the code, it results in the following error: Error in src/main.ts (11: ...

Steps to run the node application on a temporary different port:

In my application, the current configuration looks like this: module.exports = { 'port': process.env.PORT || 8080, 'database': 'mongodb://xxx:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7 ...

Utilizing p5 SVG for interactive graphics in a web application with a React front-end and an Express back-end

I have implemented a p5.js code utilizing SVG canvas from the https://github.com/zenozeng/p5.js-svg library. In my React frontend, I aim to display the visuals generated by this p5.js script. However, a challenge has emerged as React's existing librar ...

Troubleshooting: Why is my console.log not working in JavaScript

Recently, I've been diving into the world of JavaScript, but for some reason, I can't seem to make console.log function properly. At the top of my HTML document in the head section, I added jQuery like this: <script type="text/javascript" sr ...

Can angular and grunt support multiple run blocks simultaneously?

Currently, I am configuring $httpBackend to simulate fake API routes while our team of API developers is building them out. However, I am facing an issue where I have to place all the $httpBackend configurations within my run block. This leads to a situa ...

Automatically generate sitemap with Node.js and Express for a seamless crawling experience

My website content is updated regularly, and I am looking for a solution to automatically generate a new sitemap every day. I attempted to utilize sitemap.js, but it requires manual entry of specific URLs from my site. I am curious if there exists a meth ...

Unpredictable hues in a headline

Can the text in an H1 tag have each word appear in a different random color, and then refresh to show new random colors? I have 5 specific colors in mind that I'd like to use. How would I go about coding this? ...

"Enhance Your Website with Slider Swipe Effects using CSS3 and

After scouring the internet for various types of sliders, including swipe sliders, I am interested in creating a responsive swipe slider specifically for mobile phones. This would be a full page swipe slider where users can swipe left and right seamlessly. ...

Exploring Angular Testing: Unraveling Chained HTTP Requests with the Power of rxjs

I've been attempting to write unit tests for a function in my service that carries out a POST request followed by a GET request. I'm using switchMap to handle this, but running into an issue where the HttpTestingController match function isn&apos ...

Instructions for inserting <tr></tr> after every fourth iteration of <td></td> in the loop

I am trying to create a list of twenty people with each tr containing 4 people, and I want to break from the loop after every fourth number. Each td value should be incremented in order. This is the code snippet I have been working on: <?php for ($i ...

Compilation with Webpack and Postcss failed due to the inability to locate the scss file within the library in node_modules

Here is the layout of my project structure: node_modules dist config - webpack.common.js - webpack.dev.js - webpack.prod.js - webpack.test.js src - app - app-routing.module.ts - app.component.html - app.component.scss - app.compo ...

Can you help me streamline the code for the Sign Up Form app using React and jQuery?

Hi everyone, this marks my debut post on StackOverflow as I embark on the journey to become a full stack developer. To enhance my skills, I've been using FrontEnd Mentor for practice and managed to solve a challenge with the code provided below. Any s ...

The issue with JQGrid: Inaccurate selection of drop down value when edit type is set to 'select'

I am currently using JQGrid 4.4.4 and have encountered an issue with a column set to edittype = 'select'. While the value displayed in the grid row is correct, the drop-down or combo-box value is being set to the wrong value when editing the row. ...

Angular 2 FormArray validation based on conditions

My goal is to apply validation rules based on changes in one field to another field within a formGroup that is nested inside a FormArray containing multiple instances of this group. Specifically, when the date field is modified, I need the Reason for Chang ...