Do you have any suggestions on how I can incorporate a header into this function?

Can anyone advise on how to include a header in the function below? I have created a login service and receive a status of 200 in response. However, when attempting to send a GET request afterwards, I encounter the error message

Failed to load resource: the server responded with a status of 403 (Forbidden).

  func() {
    return this.http.get('/data', )
        .map(response => response.json())
        .subscribe(response2 => this.response2 = response2);
}

My GET:

get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return super.get(appConfig.apiUrl + url, this.addJwt(options)).catch(this.handleError);
}

 private addJwt(options?: RequestOptionsArgs): RequestOptionsArgs {
        // ensure request options and headers are not null
        options = options || new RequestOptions();
        options.headers = options.headers || new Headers();

        // add authorization header with jwt token
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (currentUser && currentUser.token) {
            options.headers.append('Authorization', 'Bearer ' + currentUser.token);
        }

        return options;
    }

SOLUTION The issue was that the backend expected the Token format to be sent as Token 132083128901302, but I was sending it as Bearer 132083128901302. After changing from Bearer to Token, everything started working correctly.

Answer №1

const myHeaders = new Headers({ 'Authorization': 'Bearer ' + jwt });
const requestOptions = new RequestOptions({ headers: myHeaders });
return this.http.get('http://test.dev/get/user', requestOptions).map(response => response.json());

Using interceptors through the HttpClient Module is highly recommended. It simplifies implementation, reduces code in the application, and makes management easier.

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

Returning a List in JSON format using WCF REST

Is there a way to return a List of Users in JSON format using WCF with Rest? My Endpointconfiguration is already functioning properly. [OperationContract(Name = "GetUsers")] [WebGet(UriTemplate = "GetUsers", ResponseFormat = WebMessageFormat.Json, Reque ...

Disable dates that are more than 7 days from the current date using Material UI's Date

How can I restrict users from selecting dates more than 7 days after their initial selection? In the example image provided, the date of January 30th should be disabled for selection. https://i.stack.imgur.com/iTem4.png Below is the code snippet: const ...

Comparing NativeScript and Flutter

Currently diving into the world of Native Script with Angular, I am fascinated by the code sharing capabilities that allow me to work on both web and mobile applications. However, a lingering question in my mind is why Google chose to develop Angular for ...

Troubleshooting Angular 4 Routing Problems

I am facing an issue with Angular where the components I configure to load at the empty '' path are not rendering properly. Below is a breakdown of my project structure: project/ |- app/ | |- landing-page/ | |- second-page/ | |- third-pag ...

Converting a "String" value to a specific "Type" in Angular 2 using TypeScript

This is my current object, Home points to the import statement for Home component. import { Home } from '../home/home'; arr = [ { name: "Home", root: Home, icon: "calc" } ]; This is what I want to achieve: import { Home } from & ...

Guide to eliminating a tiny caret from ion-select in Ionic 4

Is there a way to replace the default grey caret in ion-select with a custom arrow? Here is my current CSS code: ion-select { color: grey; background:url("/assets/resources/img/ArrowDownConfig.svg"); } Unfortunately, my custom arrow is not taking pr ...

First, download a npm package and integrate it into TSX files

Hello all, I am currently working on my very first project using React, Typescript, and ASP.NET Core. As a beginner in this technology stack, I seek your patience and understanding as I encounter challenges along the way. Right now, I'm facing an issu ...

TS-2304 Error - 'Iterable' not found in TypeScript when trying to import 'jquery' into a '.ts' file

Currently, I am utilizing TypeScript version 2.4 in Visual Studio Code for development. My approach involved installing jQuery via NPM using the given command: npm install --save @types/jquery Subsequently, I obtained the source code for the jquery modul ...

Guide to integrating a legend with ngb-timepicker form?

Is there a way to add a specific tag to the fieldset of ngb-timepicker? I'm having trouble finding a solution for this. Has anyone else tried to do this before? ...

Create interfaces for a TypeScript library that is available on npm for export

I have a project in TypeScript that I am packaging as a library to be used by both JavaScript and TypeScript projects. After compiling, I upload the .js and .d.ts files to npm. The main.ts file exports the following: interface MyInterface{ // ... } clas ...

What is the process for converting variadic parameters into a different format for the return value?

I am currently developing a combinations function that generates a cartesian product of input lists. A unique feature I want to include is the ability to support enums as potential lists, with the possibility of expanding to support actual Sets in the futu ...

How can 'this' be converted from D3 JavaScript to TypeScript?

In JavaScript, 'this' has a different meaning compared to TypeScript, as explained in this informative article 'this' in TypeScript. The JavaScript code below is used to create a thicker stroke on the selected node and give smaller stro ...

Can you dynamically create screens within the React Navigation Tab Navigator using code?

My goal is to dynamically generate tabs in React-Navigation based on the values retrieved from an array, and pass the data from each array value to the corresponding screen. For instance, if there are 2 accounts, I expect 2 tabs with unique screens for eac ...

Ways to manually initiate a change detection in a ComponentRef

Trying to create a dynamic component and initiate a change detection using the ComponentRef. Attempted to generate a dynamic component and induce a change detection through the ComponentRef, but encountered difficulties. The component failed to trigger th ...

Creating a list of components for drag and drop with Angular CDK is a straightforward process that involves following

I am attempting to use Angular's CDK drag and drop functionality to create a list of components that can be rearranged. However, I am encountering an issue where the components are not being displayed correctly. In my App.component.ts file: impo ...

What is the significance of utilizing an empty value `[]` for a typed array interface instead of using an empty `{}` for a typed object interface?

Why can I initialize friends below as an empty array [], but not do the same for session with an empty object {}? Is there a way to use the empty object without needing to make all keys optional in the interface? const initialState: { friends: Array< ...

What is the process of bringing in a Svelte component into a Typescript file?

Can a Svelte component be imported into a Typescript file and successfully compiled by Rollup? While the following code works fine as a Javascript file, it encounters errors when converted to Typescript, as the TS compiler struggles with a .svelte file: i ...

If I include the Next.js Image component within a React hook, it may trigger the error message "Attempting to update state on an unmounted component in React."

My UI layout needs to change when the window width changes. However, when I add an Image (Nextjs component) in my hook, I encounter an error message. I am not sure why adding Image (Nextjs component) is causing this problem. The error message is display ...

Iterating over elements with a custom width using ngFor in Bootstrap

I'm currently using *ngFor to cycle through multiple images as the background of each column in a row using Bootstrap. One thing I'm wondering is how to control the width of each column. For example, if I have 10 images, how can I adjust the widt ...

Encountering a problem with updating values in local storage using ReactJS

My goal is to store values in local storage, but I am facing an issue where it saves an empty array in local storage the first time I click on Set Item. After the initial setup, the code works as expected. I am relatively new to React and TypeScript. Below ...