0

I've been fighting this problem for the last 3 weeks. I don't know if I'm also doing something wrong at the moment of connecting the API to the Front end not being able to at least print the JSON given from the API. Funnily enough the API seems to work by itself, getting the info without problems.

The problem is: at the moment of trying to print the JSON, the service tell shows me this on the debugger in Firefox:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:7299/api/Customers/GetAll/2. (Reason: CORS request did not succeed). Status code: (null).

or this if the api is set to http, the service just tells gives me the 404 error.

The API was given to me without any documentation, so I'm here at my own, I'll give an example of getting the Customers. The lead engineer told me that could be some configuration on my computer, but he didn't give any specifics. I don't know if I need to configure a server or something, I feel so lost.

This is the controller of the API for the GET method for Customers

[Route("api/[controller]/[action]")]
[ApiController]
 
//GET CustomerController       
[HttpGet("{nmov}")] //where nmov is the transaction ID
public async Task<IActionResult> GetAll(int nmov)
{
    try
    {
        var oCustomers = await _context.maeclien.Where(c=> c.nmov==nmov).ToListAsync();
        return Ok(oCustomers);
    }
    catch (Exception oException)
    {
    return HandleServerError(oException, "Error", "CustomersController", "GetAll");
    }
}

These are the flies that I use to try, connect and print the JSON

//environment.developdment.ts

export const environment = {
    //e-syspago api
    server: 'https://localhost:7299/', 
    endpoint: 'https://localhost:7299', //API's url
};
//customer.service.ts

import { computed, inject, Injectable } from '@angular/core';
import { environment } from '../../environments/environment.development';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { CustomerModel } from '../models/customer.model';
import { toSignal } from '@angular/core/rxjs-interop';

@Injectable({
  providedIn: 'root',
})
export class CustomerService {

  urlEndpoint = computed(() => `${environment.endpoint}/api/Customers/GetAll/2`);
  private http = inject(HttpClient)

  private customer$: Observable<CustomerModel[]> = this.getCustomers();
  public customer = toSignal(this.customer$, {initialValue:[]});

  getCustomers(): Observable<CustomerModel[]> {
    return this.http.get<CustomerModel[]>(this.urlEndpoint());
  }
}
//customers.ts

import { CommonModule } from '@angular/common';
import { Component, CUSTOM_ELEMENTS_SCHEMA, inject, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ButtonModule } from 'primeng/button';
import { TableModule } from 'primeng/table';
import { CustomerModel } from '../../models/customer.model';
import { CustomerService } from '../../services/customer.service';
import { environment } from '../../../environments/environment.development';

@Component({
  selector: 'app-customers',
  imports: [CommonModule, TableModule, ButtonModule],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  templateUrl: './customers.html',
  styleUrl: './customers.css',
})
export class Customers implements OnInit{
  customer!: CustomerModel[]
  service = inject(CustomerService);

  ngOnInit() {
    console.log(environment.endpoint) //prints the endpoint from the environment file
    this.service.customer
    console.log(this.service.customer) //prints the JSON
  }
}

If anyone please can help me, I will be so glad!!!

2
  • The (null) status suggests the request would have failed even if it were same origin. So check just a manual navigation to that URL. (plug " localhost:7299/api/Customers/GetAll/2 " into the url bar of the browser and see what happens... if that's fine, check the server to see if it responds to an OPTIONS verb. Might also check "HandleServerError" method and see what that's doing. Also note that the error is showing http, not https as in your environment file. (see what your this.urlEndpoint() is returning?) computed doesn't seem right there... those should be constants, no? Commented Nov 20 at 21:01
  • you might also be misunderstanding the use of the environment files... ng serve and ng build will choose different files (one will be renamed/replaced) so that build would have real domain value. (I say that because you've used "environment.development" in import. Usually that would just be "environment" and you'd have a fileReplacements section in angular.json. (for either "production" or "development") Not sure why you'd use computed signal there... Commented Nov 20 at 23:32

1 Answer 1

1

You have to enable CORS. It should be like this:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAngularDev",
        policy =>
        {
            policy.WithOrigins("https://localhost:4200", "http://localhost:4200") 
                  .AllowAnyMethod()
                  .AllowAnyHeader();
        });
});

var app = builder.Build();

app.UseCors("AllowAngularDev");
...
Sign up to request clarification or add additional context in comments.

1 Comment

the API apprently already has its CORS set up builder.Services.AddCors( options => { options.AddDefaultPolicy( builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() ); } ); var app = builder.Build(); app.UseCors();

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.