1

Mozilla dev tab network tabDetails of GET method called to 5001

I forced a problem which I cannot solve since several hours, it's quite common, however none of tips found online helped me.

Answer body

Everything is on my local PC. Firstly I developed some simple ASP.NET Core WebAPI on Core 2.1 using VS Code and command line. This WebAPI has currently one simple APIController which is hosted on adress: https://localhost:5001/api/customers/1 (when I paste it on browser or postman as result I have some simple Json returned with data of one customer from database). Of course in Startup.cs class I added:

app.UseCors(options => 
            options.WithOrigins("http://localhost:4200/")
            .AllowAnyMethod()
            .AllowAnyHeader());

and I have a filter also:

    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

Which is added into every method inside controller and above controller API declaration.

Whole controller code:

namespace BackEnd.Controllers
{
    [AllowCrossSiteJson]
    [Route("api/[controller]")]
    [ApiController]
    public class CustomersController : ControllerBase
    {
        private readonly ICustomersRepository _customersRepository;

        public CustomersController(ICustomersRepository customersRepository)
        {
            _customersRepository = customersRepository;
        }



        // GET api/customers
        [HttpGet]
        public async Task<string> Get()
        {

            var customer = await _customersRepository.GetRandomCustomer();

            return customer.FirstName.ToString();

           // return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [AllowCrossSiteJson]
        [HttpGet("{id}")]
        public async Task<Customer> Get(int id)
        {
            var customer = await _customersRepository.GetCustomerById(id);
            return customer;
        }

        // POST api/values
        [HttpPost]
        public async Task Post([FromBody] Customer customer)
        {
             await  _customersRepository.SaveCustomer(customer);

        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

I am using google Chrome browser.

Second - I have separate project developed with Node.Js in Angular 6.1.1. I wanted to do a quick test and call to Web API from Angular app. So Inside AppComponent I added proper httpClient injection and inside OnInit method I added http.get request like this :

this.httpClient.get(`https://localhost:5001/api/customers/${id}`);

My Angular app originally is server by Node.js on adress http://localhost:4200 on my PC. (In the same time both WebAPI and Angular apps are running on my PC - two tabs are opened in the same Google Chrome)

When I launch to http://localhost:4200 and opened Google Chrome Developer tab in console there is an error :

Access to XMLHttpRequest at 'https://localhost:5001/api/customers/1' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What I found online is that this problem comes from browser (Postman normally can consume data from WebAPI) I tried to add to mine angular file proxy.conf.json with content:

{ 
    "/api/*": {
        "target": "https://localhost:5001",
        "secure": false,
        "changeOrigin": true
    }
}

But it did not help me at all. I have no idea where to look at.

Angular code:

export class AppComponent {
  title = 'FrontEnd';

  constructor(private apiService: ApiService) { }

  ngOnInit(){
      console.log('hello');
      this.apiService.getCustomerById(1).subscribe((res) => {
         console.log(res);
      });
  }

  public getCustomerById(id :number) {
      return this.httpClient.get(`https://localhost:5001/api/customers/${id}`);
  }
}
Stphane
  • 3,368
  • 5
  • 32
  • 47
user3662082
  • 11
  • 1
  • 4
  • Please show your controller definition and the endpoint definitions inside the controller, with all attributes. Please also use Firefox and make a screenshot of the dev panel's network tab there, it shows a few things the Chrome dev tab omits. I suspect the OPTIONS request is not coming back because there is no endpoint that can serve the OPTIONS request, so I believe just returns a generic 404. – Alexander Jul 07 '19 at 19:38
  • Also can you try to put the referer into the response header? Sometimes, browsers have problems with `*`. IIRC the standard says that servers "should reply with the same value" the user agent sends. – Alexander Jul 07 '19 at 19:41
  • @Alexander - sorry I don't understand what you mind in second comment, I added controller definition – user3662082 Jul 07 '19 at 19:45
  • Link to mozilla network tab is in 1st line of my post. – user3662082 Jul 07 '19 at 19:52
  • In console in mozzila I still get: „https://localhost:5001/api/customers/1” (brakujący nagłówek CORS „Access-Control-Allow-Origin”) – user3662082 Jul 07 '19 at 20:01
  • According to everything I find, the attribute you use is only suitable for MVC controllers, not for WebAPI controllers. Can you closely follow the tutorial from https://learn.microsoft.com/de-de/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api and see whether that helps? – Alexander Jul 08 '19 at 09:10
  • No - it didn't help me at all ! :/ – user3662082 Jul 08 '19 at 18:50
  • I added "Answer body" picture of details of response from WebAPI in mozilla tool. – user3662082 Jul 08 '19 at 18:54
  • I added also CORS extension to mine Chrome and it still didn't help me :/ – user3662082 Jul 08 '19 at 19:18
  • SOLVED !!!I I added .AllowAnyOrigin() line to UseCors() – user3662082 Jul 08 '19 at 19:55

2 Answers2

2

The issue is with your server, not with angular. You need to set your web api to allow cross origin resource sharing. You do this by adding additional headers to your web api response.

To see how to do this; read this answer

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

larisoft
  • 191
  • 2
  • 5
1

Web browsers prevent a webpage from making requests to a different different domain than the one that served the web page. This is called same-origin policy. For every such request, an OPTION call is made by the browser which looks for Access-Control-Allow-Origin header. The requesting domain should be included in that header. You need to enable this by making few changes in your ASP.NET CORE project.

This post might be useful: https://stackoverflow.com/a/31942128/4395295

rishav
  • 441
  • 9
  • 27