简体   繁体   中英

Angular: HTTP GET request - OPTIONS 405 (Method Not Allowed)

I'm trying to make an HTTP GET request to my API, and it returns OPTIONS 405 (Method Not Allowed) and

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.

Below is my code:

 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 tried to do the same in Postman, C# Console App, and in ASP.NET WebForms, it worked perfectly, but in Angular I get the error mentioned above. I have a HTTP GET request for my login also in TypeScript which WORKS PERFECTLY .

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

UPDATE: Thank you guys, just to let you know I ended up using Flask with angular to make requests and it is brilliant.

This is a CORS issue. Your webserver hosting the REST APIs is running on a different domain than the webserver hosting the Angular static files.

Make sure you are not running your Angular on localhost and REST APIs on a separate domain or something similar. Ideally you should run both from the same domain.

Configure the REST API hosting server to allow the CORS from the Angular hosting server (localhost).

Postman wouldn't have any problems getting the resource here.

But as your request from Angular server is getting a Cross Origin error, you need to get the backend set with the API having your angular server address set in the Access-Control-Allow-Origin header for you to get the access of the requested resource.

If you set the Access-Control-Allow-Origin header with *, it would allow any server to get the resource but this isn't secure as anyone could get your resources without your permission.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM