0
votes

I have this service:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class LoginService {

  constructor(private http: HttpClient) {}

  getUsers() {
    const options = {
        headers: new HttpHeaders({
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Methods': 'GET',
          'Access-Control-Allow-Headers': 'Origin, Content-Type',
          'Content-Type': 'text/xml'
        })
      };

    return this.http.get('myurl', options);
  }
}

And I'm trying to access an API which has only GET. This particular resource allows anonymous access.

However, I get the following errors (in Chrome console):

OPTIONS myurl 405 (Method Not Allowed)

Failed to load myurl: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 405.

Any ideas on how to fix these errors?

3
The error says that th requested resoucre does not allow you to pass. Consider adding headers to the backend you want to accessto allow your localhost.4200BrianM
Your server (not the angular app) needs to allow this URL: localhost:4200. If your API is written in C# then you need to allow this in Startup.csDaniel
Is there any error if you try to access it directly from the browser?John Velasquez

3 Answers

1
votes

Assuming you are dotnet core.

Taken from the MSFT Docs: you need to allow CORS in Startup.cs like:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole();

    // Shows UseCors with CorsPolicyBuilder.
    app.UseCors(builder =>
       builder.WithOrigins("http://localhost:4200"));

UPDATE when using .ASPNet WebApi2

Taken from the MSFT Docs: there are many ways how to implement a CORS policy. One example is: in File WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // New code
        config.EnableCors();

        // existing code
    }
}

and then in your Controller:

[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
public class TestController : ApiController
{
    // Controller methods not shown...
}
1
votes

Even though your frontend is set up to include the access control headers, the backend you are trying to access is not configured to accept your origin. If you have control of the backend you are trying to access i.e if you can change the code, you need to update it to either allow all OPTIONS requests, or alternatively configure it to allow your localhost:4200 origin.

If you do not have access to making changes in the backend, you can serve your application through a proxy. Adding a proxy.conf.json with the following contents should be enough:

{
    "/": {
        "target": "myurl",
        "secure": false
    }
}

where myurl is the url to the backend api. Then when starting up the application, include the proxy config location:

ng serve --proxy-config proxy.conf.json
0
votes

The error says that the requested resource does not allow you to pass. Consider adding headers to the back end you want to access to allow your localhost:4200 since it will not let it through