Angular fails to include the values of request headers in its requests

Using Django REST framework for the backend, I am attempting to authenticate requests in Angular by including a token in the request headers. However, Angular does not seem to be sending any header values. Despite trying various methods to add headers to the request.

test(){
    let token='Token '+'d7dd1e453bae5086e33243b9adca5b63d2d927fb8';

    const httpOptions = {
      headers: new HttpHeaders({

        'Authorization':'Token d7dd1e453bae5086e33243b9adca5b63d2d927fb8',
        'Content-Type': 'application/json', 
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers':'X-Requested-With'

      })
    };
    console.log(token);
    this.http.get('http://localhost:8003/hello/', httpOptions).subscribe(

      response=>{console.log(response);}

    );
  }

Access-Control-Request-Headers: access-control-allow-headers,access-control-allow-origin,authorization,content-type Access-Control-Request-Method: GET DNT: 1 Origin: http://localhost:4001 Referer: http://localhost:4001/

Answer №1

While working on a recent project, I encountered a similar issue and was able to resolve it by configuring the headers as shown below:

let headers = new HttpHeaders().set('Authorization', 'Token ...')
                               .append('Content-Type', 'application/json')
                               .append('Access-Control-Allow-Origin', '*')
                               .append('Access-Control-Allow-Headers', 'X-Requested-With');

 // You can then choose either of these methods:
 const httpOptions = { headers: headers };
 this.http.get('http://localhost:8003/hello/', httpOptions);

 // or
 this.http.get('http://localhost:8003/hello/', { headers: headers });

Best regards.

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

Extracting Date and Time Information from matDatepicker in Angular 6 Material

Below is the code snippet present in my html file: <mat-form-field> <input matInput [matDatepicker]="myDatepicker" placeholder="Choose a date" [(ngModel)]="model.value" name="value"> <mat-datepicker-toggle matSuffix [for]="myDatepic ...

incorporating numerous interconnected javascript files within a single html document

I have a pair of JavaScript files (file1, file2). File1 utilizes a class that is defined in file2. Can I include these files in an HTML document like this: <script type="text/javascript" src="file1.js"></script> <script type="text/javascrip ...

Showing user data in a div using JavaScript ajax without the use of jQuery

Recently diving into the world of javascript and ajax, I find myself tinkering with code on jsfiddle. My current goal is to populate a list with usernames and emails upon form submission. Upon submitting the form, an error message pops up: {"error":"key m ...

Unable to retrieve parameter while making a POST request

Need some help with attribute routing. I'm having trouble getting parameters from the HTTP body. The ConnectionID Class includes a property named CValue. $('#btn').click(function () { $.ajax({ type: "POST", url: "http:// ...

Transform Angular into a library

I've been exploring different options but still haven't nailed down the best approach. I've developed an Angular library with custom components, which I'm converting into Web Components to be used in non-Angular applications. But to mak ...

Retrieve JSON data by making an AJAX request to a PHP file using the POST method

I am looking to extract data from a form using an AJAX call. The information is received in PHP as a string that looks like: 'fname':'abc','lname':'xyz','email':'','pass':'',& ...

Combining Django with the powerful Vue3 and lightning fast Vite

I'm in the process of upgrading my multipage app from Vue2 with webpack to Vue3 with Vite. After successfully rendering my Vue3 components on my Django templates, I am now facing a challenge - setting component variables on the Vue app using the Djan ...

Utilizing Typescript for Efficient Autocomplete in React with Google's API

Struggling to align the types between a Google address autocomplete and a React-Bootstrap form, specifically for the ref. class ProfileForm extends React.Component<PropsFromRedux, ProfileFormState> { private myRef = React.createRef<FormContro ...

What is the solution to resolving the warning about the router no longer defaulting the history prop to hash history?

I have implemented browser history in my code within routes.js export default ( <Router history={browserHistory}> <Route path="/" component={Main}> <Route path="home/:username" component={Home}> <IndexRoute co ...

Utilize the identical element

Incorporating the JwPaginationComponent into both my auction.component and auctiongroup.component has become a necessity. To achieve this, I have created a shared.module.ts: import { NgModule } from '@angular/core'; import { JwPaginationCompon ...

Tips for transferring information between concatMap operators in RXJS in an Angular application

I am working with an observable pipe that looks like this: .pipe( concatMap(() => this.security.getUser()), tap((partyId) => { if (!partyId) { window.location.assign(`${environment.redirectURL1}/dashboard/login`); } }), concatMap( ...

We were unable to load the resource because the server returned a 404 (Not Found) error. The EnterpriseMaster/BindNatureofAssignment feature is not functioning properly after being published

While the code is working perfectly fine on localhost, as soon as I publish it I encounter an error that prevents the table from loading. EnterpriseMaster/BindNatureofAssignment:1 Failed to load resource: the server responded with a status of 404 (Not ...

Craft dynamic SVG components using TypeScript

Looking to generate a correctly formatted SVG element using TypeScript: createSVGElement(tag) { return document.createElementNS("http://www.w3.org/2000/svg", tag); } Encountering an issue with tslint: Error message: 'Forbidden http url in str ...

Exploring complex nested data structures

I've been tackling a component that manages labels and their child labels. The data structure and rendering process are sorted out, as shown in this example. However, I'm at a roadblock when it comes to manipulating the data effectively. Specif ...

Modify the chosen dates in the date range picker tool designed for Twitter Bootstrap

I recently started using the date range picker for Twitter Bootstrap, a creation by Dan Grossman, which you can find here. Upon initialization, I realized that setting pre-defined values like startDate and endDate was possible. However, my question is: Is ...

Checkbox acts like radio buttons in JavaScript

Currently, I have a unique setup where a table is generated dynamically based on the user's selection from a dropdown. Within this table are three checkboxes per row, with a limit of 2 checkboxes that can be checked per row. The behavior of Checkbox ...

The element is implicitly assigned to an 'any' type due to the inability to use a 'string' type expression to index the 'Breakpoints' type

I have a question related to TypeScript that I need help with. My objective is to create a custom hook for handling media queries more efficiently. Instead of using useMediaQuery(theme.breakpoints.down('md');, I want to simplify it to: useBreakP ...

Is the functionality compatible with all browsers even though <div /> is not recognized as a proper HTML element?

Can the code $("<div />").appendTo($mySelector) be relied upon for safety and cross-browser compatibility, considering that <div /> is not a valid HTML element? I pose this question because it seems much simpler to use than $("<div><d ...

Is there a way to identify the moment when a dynamically added element has finished loading?

Edit: I've included Handlebar template loading in my code now. I've been attempting to identify when an element that has been dynamically added (from a handlebars template) finishes loading, but unfortunately, the event doesn't seem to trig ...

Arranging and Filtering an Object Array Based on their Attributes

Here is an example of a JSON array called items: var items = [ { Id: "c1", config:{ url:"/c1", content: "c1 content", parentId: "p1", parentUrl: "/p1", parentContent: "p1 content", } }, { Id: "c2", ...