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?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • 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 – BrianM May 03 '18 at 07:52
  • Your server (not the angular app) needs to allow this URL: http://localhost:4200. If your API is written in C# then you need to allow this in Startup.cs – Daniel May 03 '18 at 07:52
  • Is there any error if you try to access it directly from the browser? – John Velasquez May 03 '18 at 08:10
  • this might help: https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api – Ric May 03 '18 at 08:21
  • Possible duplicate of [XMLHttpRequest cannot load https://www.\[website\].com/](https://stackoverflow.com/questions/35553500/xmlhttprequest-cannot-load-https-www-website-com) – Quentin May 03 '18 at 08:22
  • `Access-Control-*` headers are **response** headers, they have no place on the request where you re putting them. – Quentin May 03 '18 at 08:22
  • `Content-Type`, when used as a request header, describes the data you are sending **to** the server, not the data you expect back. It has no place being on a GET request. – Quentin May 03 '18 at 08:23

3 Answers3

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...
}
Daniel
  • 9,491
  • 12
  • 50
  • 66
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
Ntokozo Zwane
  • 1,572
  • 14
  • 20
  • I've added the file to the root of my Angular project, started it again, but I still get the same error. – Ivan-Mark Debono May 03 '18 at 08:05
  • @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 – Ntokozo Zwane May 03 '18 at 08:19
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

BrianM
  • 951
  • 2
  • 12
  • 29