Angularjs: Request $http to consume the domain’s external API giving error

Asked

Viewed 48 times

1

I have an Angularjs application that logs in. I am trying after logging in, requesting an API that I am running on my machine running in C# to at least be able to communicate with it. But it made several mistakes in my attempt, since

  $http.get('http://localhost:5001/Login').then(function(data){
     console.log('entrou algo');
  }, function(data){ console.log(data); });

Error 1: Blocked cross source request: Same source policy does not allow reading the remote resource at http://localhost:5001/Login. (Reason: the CORS application was unsuccessful)

    $http({method:'GET',
           url: 'https://localhost:5001',   
           headers: 'Access-Control-Allow-Origin: *'
         }).then(function(data){
        return data;        
    });

Erro2: Blocked cross source request: Same source policy does not allow reading the remote resource in https://localhost:5001/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Someone could help me?

  • 1

    you have to configure the service to accept and release the cors!

  • I tried to put in index.php, in . htacess and still by the request and still continues with the error. I don’t know if I did right too...

  • 1

    what if there is index.php with C#?

1 answer

1


Your problem does not seem to originate in the client where the Angularjs snippet is running.

Assuming your API is written in . NET Core 3.1, the solution would be to add policies which allow local access.

Configuration example:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(name: "Acesso Local",
            builder =>
            {
                builder.WithOrigins("http://localhost") // <- URL do conteúdo AngularJS
                        .WithMethods("PUT", "DELETE", "GET");
            });
    });
}

public void Configure(IApplicationBuilder app)
{
    app.UseCors();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.