Angular interceptor alters headers and updates request method

My Angular HTTP interceptor is trying to add Authorization headers to a request, but when the code runs, the resulting request does not behave as expected. The method changes from POST to OPTIONS and an error message is generated:

Access to XMLHttpRequest at 'http://localhost/authorization/oauth/token' from origin 'http://localhost:4200' has been blocked by CORS policy. The response to the preflight request fails access control checks and does not return an HTTP ok status.

@Injectable()
export class DlkmInterceptor implements HttpInterceptor {

 constructor() {
 }

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

   if (request.url === authConfig.tokenEndpoint && request.method === 'POST') {
     let authData = window.btoa(authConfig.clientId + ':' + authConfig.dummyClientSecret);
     request = request.clone({
       setHeaders: {
         'Content-Type': 'application/x-www-form-urlencoded',
         'Authorization': 'Basic ' + authData
       }
     });
     return next.handle(request);

   } else {
     request = request.clone({});
     return next.handle(request)
   }

 }
}

Answer №1

This behavior is to be expected, as it is a result of the browser's Cross Origin Policy.

When you request a resource from a different domain than the one hosting your Angular Application, the browser adheres to the Cross Origin Policy.

Before allowing the actual request, the browser first sends an OPTIONS request, also known as a preflight request, to check if the resource can be requested.

To ensure a successful preflight request, you must allow the necessary headers on your backend server. Once the preflight request is successful, the browser will proceed with the actual request.

If you want to delve deeper into this topic, you can find more information here.

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

Changing the Type of Angular Property from SignalFunction to Boolean

Seeking insights on a curious situation in my Angular app. Here's the issue: I have a code snippet with a property named isSelection defined like this: public isSelection = model.required<boolean>(); public getTypeof(value: any): string { re ...

What is the process of updating a value with Angular Material after selecting a new value?

I want to implement the angular material Datepicker for selecting dates and updating a value once a date is chosen. The code below successfully updates the value when typing in the Datepicker input field, but not when selecting a date from the Datepicker t ...

Error TS2339 occurs when the property "classes" is not found in the type "PropsWithChildren"

I have encountered a typescript error while transitioning our files to typescript. As a newcomer to typescript, it has been quite challenging for me to search for solutions online. My approach is to grasp the error first before delving into finding a resol ...

Using Typescript to specify the parameter type of a function as a generic function

After creating a function called compose, it looks like this: const composeTyped = <T, U, R>(f: (x: T) => U, g: (y: U) => R) => (x: T) => g(f(x)); It appears to me that both functions f and g fall under the type fGeneric, which is define ...

Unable to locate 'this' in the callback function triggered by tinymce

I am experiencing an issue with my Angular2 app that uses tinyMce as an HTML editor. The problem arises when I need to convert the URLs in the HTML content using my REST API. I tried using the "urlconverter_callback" function from tinyMce, but I encountere ...

The object literal is limited to defining familiar properties, and the 'entryComponents' property is not present in the 'NgModule' type

After updating my Angular version from 11 to 17.3.8, I encountered errors in my code whenever I used entry components in @NgModule. This resulted in errors within all npm modules when running locally. import { NgModule } from '@angular/core'; imp ...

Ensure the presence of a value in an array using Angular

I need to check if any of the "cuesData" have values or lengths greater than 0. However, in my current code, I can only evaluate the first array and not the rest. https://i.sstatic.net/bMpvg.jpg TS checkValues(values) { const result = Object.values ...

Avoiding data type conversion in JavaScript/TypeScript

Currently delving into the world of JavaScript, I come from a background of working with statically typed languages. Naturally, I opted to dive into TypeScript instead of starting directly with JS. While TypeScript is great and addresses many issues presen ...

Understanding 'this' in ChartJS within an Angular application

Here is my event handler for chartJS in Angular that I created: legend: { onClick: this.toggleLegendClickHandler After changing the text of the y scale title, I need to update the chart. I am looking to accomplish this by calling this._chart.cha ...

Utilize static information within an Angular component

I'm working on an Angular project in my localhost and I want to have two routed components that share the same data. One component will display the data, while the other will handle the data. In simpler terms, I need two webpages: one with an input f ...

transmit data from Node.js Express to Angular application

I am making a request to an OTP API from my Node.js application. The goal is to pass the response from the OTP API to my Angular app. Here is how the API service looks on Angular: sendOtp(params): Observable<any> { return this.apiService.post(&q ...

Angular's focus function poses certain challenges that need to be addressed

I am seeking assistance as a new programmer facing a beginner's challenge. I have two inputs and I would like to enter a series of numbers in the first input (DO) and have them automatically populate in the second input (communal code). Inputs: http ...

Ways to extract a specific value from a geojson object using the key name

After making a call to the back-end, I retrieved the below geojson data in the 'data' object. However, when trying to access the values of the 'type' and 'features' keys within the geojson, I encountered difficulties. data["g ...

My code is ready, but unfortunately, it is not retrieving the data as expected from my JSON file

I'm encountering an issue with my code where it's not fetching data from my JSON file. I keep getting 0 arguments and I'm unsure of what I'm doing wrong. Can someone provide assistance? This project is built using Angular. I have my ...

Struggling to configure Sass with @snowpack/app-template-react-typescript

I'm struggling to integrate Sass with the @snowpack/app-template-react-typescript template. I attempted to follow the steps outlined in this guide, but so far I haven't been successful. I even created a new project and tried adding it, but not ...

Creating a canvas that adjusts proportionally to different screen sizes

Currently, I am developing a pong game using Angular for the frontend, and the game is displayed inside an HTML canvas. Check out the HTML code below: <div style="height: 70%; width: 70%;" align="center"> <canvas id=&q ...

What is the best way to effectively personalize my Bootstrap variables using SASS?

After creating a web page and adding Bootstrap styling, I attempted to customize the Bootstrap variables, but encountered an issue where it did not seem to work despite no errors being displayed. I followed a tutorial on YouTube meticulously, but to no av ...

List out all the classes that implement an interface in Typescript

Greetings to all TypeScript enthusiasts! Here's a challenge I want to tackle: I aim to establish an interface -- let's name it IShape -- and define several classes (Rectangle, Circle, Triangle) that adhere to the IShape interface. Let's sa ...

Tips on how to access the names of all properties within a TypeScript class while excluding any methods

Looking to enhance the reactivity of my code, I want to render my view based on the properties of a class. How can I extract only the property names from a class and exclude methods? For instance: export class Customer { customerNumber: string; ...

Tips for updating the border color of a div upon clicking it

Currently working on a project using react/typescript and facing an issue with changing the border color and width of a div upon clicking it: <div className="showroom-card " onClick={() => setSelection({ showroom: &ap ...