Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16310

Angular 5 HTTP get method not allowed when accessing WebApi

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?

Upvotes: 0

Views: 2549

Answers (3)

Ntokozo Zwane
Ntokozo Zwane

Reputation: 1742

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

Upvotes: 1

Daniel
Daniel

Reputation: 9829

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...
}

Upvotes: 1

BrianM
BrianM

Reputation: 949

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

Upvotes: 0

Related Questions