0

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?

7
  • 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.4200 Commented May 3, 2018 at 7:52
  • 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.cs Commented May 3, 2018 at 7:52
  • Is there any error if you try to access it directly from the browser? Commented May 3, 2018 at 8:10
  • this might help: learn.microsoft.com/en-us/aspnet/web-api/overview/security/… Commented May 3, 2018 at 8:21
  • Possible duplicate of XMLHttpRequest cannot load https://www.[website].com/ Commented May 3, 2018 at 8:22

3 Answers 3

1

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...
}
Sign up to request clarification or add additional context in comments.

4 Comments

Unfortunately it's not dotnet core.
well then. what is it?
Normal .ASPNet WebApi2
This is the easier solution as I have access to the backend.
1

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

2 Comments

I've added the file to the root of my Angular project, started it again, but I still get the same error.
@Ivan-MarkDebono I've updated my answer to include the last piece, I forgot to add that you need to tell the server where the proxy config is located
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.