Angular: When making an HTTP GET request, receiving an OPTIONS 405 error message indicating that the method is

I'm facing an issue with my API when making an HTTP GET request - it returns OPTIONS 405 (Method Not Allowed).

Access to XMLHttpRequest at 'apiurl' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is the code snippet:

 const header = new HttpHeaders();
 const request_header = header.append('Authorization', this.token.toString());

 console.log(request_header.get('Authorization'));

 this.urlList = buildUrl('myurl/', {path: 'mypath'});

 return this.http.get(this.urlList,{headers: request_header} );

I've tested the same request in Postman, C# Console App, and ASP.NET WebForms with success, but it's not working in Angular as I'm getting the error mentioned above. However, my login HTTP GET request in TypeScript is working perfectly.

**Note: I do not have access to the backend, but based on C# and Postman it works just fine.

UPDATE: Thank you, everyone. I have now integrated Flask with Angular for making requests, and it's working brilliantly.

Answer №1

The issue here is related to Cross-Origin Resource Sharing (CORS). Your webserver that hosts the REST APIs is on a different domain than the one hosting the Angular static files.

Ensure that your Angular application and REST APIs are not on separate domains, especially if one is on localhost and the other on a different domain. It's best to have both on the same domain for smoother functionality.

To resolve this, you need to configure the REST API server to allow CORS from the Angular hosting server (localhost) to establish the necessary connection.

Answer №2

Although Postman would not encounter any difficulties accessing the resource here, your request from the Angular server is facing a Cross Origin error. In order to resolve this issue, you must configure the backend to include your Angular server address in the Access-Control-Allow-Origin header, granting you access to the requested resource.

Setting the Access-Control-Allow-Origin header to * would allow any server to obtain the resource, but this method is not secure as it permits unauthorized access to your resources.

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

Angular Material Datepicker with Selectable Date Range

In my project using Angular 8, I needed to incorporate a datepicker with highlighted date ranges. I came across an example image here: view image. I tried to find a suitable package like the one mentioned in this link: https://www.npmjs.co ...

Why does the onBlur event function in Chrome but fails to work in Safari?

I've encountered a problem with the onBlur event in react-typescript. To replicate the issue, I clicked the upButton repeatedly to increase the number of nights to 9 or more, which is the maximum allowed. Upon further clicking the upButton, an error m ...

Unable to attach to the property 'displayQR' as it is not recognized by the 'div'?

I'm facing an issue with a div structure that looks like this <div class="empower-btn" [showQR]="showQR" [selectedCoin]="coin" [availableAmount]="getCoinAmount()" [ ...

There is a WARNING occurring at line 493 in the file coreui-angular.js located in the node_modules folder. The warning states that the export 'ɵɵdefineInjectable' was not found in the '@angular/core' module

I encountered a warning message while running the ng serve command, causing the web page to display nothing. Our project utilizes the Core Ui Pro Admin Template. Here is the list of warning messages: WARNING in ./node_modules/@coreui/angular/fesm5/coreu ...

What is the syntax for declaring a list of JSON objects in TypeScript?

I've been attempting to implement something similar to the following: interface IUser { addresses: JSON = []; } Unfortunately, it doesn't seem to be working! I'm looking to store a list of nested JSON objects inside the addresses field, ...

Troubleshooting Problem with Angular Material 2's Mat-Paginator [Length] Bug

Utilizing the mat-paginator component for a table, I am facing an issue where I am unable to dynamically set the length of the paginator based on the total number of results retrieved from an API call. Despite trying various methods like setting it in the ...

Internationalization of deferred-loaded modules within the JHipster application

I created My App using JHipster, which utilizes the JhiLanguageService in the ng-jhipster library. This service relies on the JhiConfigService to configure ngx-translate without requiring manual imports and configuration of the TranslateModule in my app.mo ...

Using JavaScript to develop a demonstration of the capabilities of Microsoft's Cognitive

Having trouble getting this basic example of the Microsoft Cognitive Services to work in JavaScript. Need some help or a working example, please! I've attempted to run the code in both node and browser with necessary modifications. Encountering an e ...

Getting a TypeError following the execution of 'npm update' and 'ng build -prod' commands

Recently, I updated my npm modules and attempted to run ng build -prod, a command that had previously been running smoothly. However, I encountered the following error: TypeError: extractedChunk.getNumberOfModules is not a function at ExtractTextPlugi ...

While attempting to update the package.json file, I encountered an error related to the polyfills in Angular

I have been working on a project with ng2 and webpack, everything was running smoothly until I updated the package.json file. Since then, I have been encountering some errors. Can anyone please assist me in identifying the issue? Thank you for any help! P ...

Issue with cordova plugin network interface connectivity

I'm currently working with Ionic 2 Recently downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface Attempting to retrieve IP addresses without utilizing global variables or calling other functions within the function ...

Using Typescript and webpack to detect variables that are defined in the browser but not in Node environment

My goal is to create a package that can be used on both servers and clients with minimal modifications required. Some libraries are available in Node but not in a browser, while others are accessible in a browser but not in Node. For instance, when utili ...

Angular Reactive Forms may not properly update other inputs when binding a control to multiple inputs

While working with reactive forms, I encountered an issue where accessing the same control in multiple inputs seemed to result in one-way data binding (input-to-model). If I make edits in one input, it updates the model correctly but does not refresh the o ...

Translation of menu item label has not been executed

Here we have a component called SidebarMenuComponent that is not translating the labels of its menu items correctly. The goal is to get the labels translated, but the current implementation is failing. What is the correct approach to apply translation in t ...

Using `new Date(device.timestamp).toLocaleString()` in React with typescript results in an invalid date

The timestamp I am receiving is in unix time format. {devices.map((device, index) => { return ( <tr key={index} className="bg-white border-b "> <td className="py-4 px-6"> {getSensor ...

Struggled with setting up the WebSocket structure in typescript

Issue Running the code below results in an error: index.tsx import WebSocket from 'ws'; export default function Home() { const socket = new WebSocket('ws://localhost:1919/ws'); return ( <div>Home</div> ); } ...

Is it possible to assign an alternative name for the 'require' function in JavaScript?

To ensure our node module is executable and includes dependencies for requiring modules at runtime, we utilize the following syntax: const cust_namespace = <bin>_require('custom-namespace'); This allows our runtime environment to internal ...

"Upon receiving a request in Net Core 6 + Angular, null properties are detected in the

Greetings! I am currently working on a project using .NET Core 6 with Angular 12. Within my project, I have a login controller along with its corresponding request model. Interestingly, when I execute the request through Swagger or Postman, everything wo ...

The promise is unexpectedly fulfilled ahead of schedule without returning the expected value from an AXIOS call

My current challenge involves making a request to a service that rapidly generates multiple strings. The problem lies in returning a promise from this service, as I lack control over the string-generation process. It is crucial for me to return a promise ...

What is the process of overriding a method from an abstract class that employs generics for typing?

In my quest to develop an abstract class with an abstract static method, I find myself wanting to override this method in a concrete class. The static nature of the method stems from its responsibility to create a 'copy' from a database model and ...