0

I'm getting the following error:

Access to XMLHttpRequest at 'https://localhost:44355/Brand' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I've tried the solutions, here, but none are working for me - the link to the Chrome plugin seems not to work. I haven't tried disabling CORS in Chrome, as that's not really the solution I'm looking for.

I'm making a GET from React:

axios
.get<BrandResponse>(url, {
  'headers': { 'Authorization': 'Bearer ' + me.props.session.credentials.accessToken } })
        .then((response: AxiosResponse<BrandResponse>) ...

And my server is a dotnet core MVC app. My controller looks like this:

[Authorize]
[ApiController]
[Route("[controller]")]
public class BrandController : BaseController
{
    ...

    [HttpGet]
    [ProducesResponseType(StatusCodes.Status202Accepted, Type = typeof(BrandResponse))]
    public async Task<ActionResult> SearchLcationsAsync([FromQuery] QueryBrand query)
        => (await QueryAsync(query)).ToActionResult();
}

And I'm adding the CORS headers in Startup.cs:

app.Use((context, next) =>
{
    context.Response.Headers["Access-Control-Allow-Origin"] = config["AllowedHosts"];
    return next.Invoke();
});

Where "AllowedHosts" is *.

Any ideas?

Paul Grenyer
  • 1,381
  • 3
  • 21
  • 44
  • Did you try postman to check if your URL works on get call? – Anglesvar Mar 12 '20 at 08:27
  • The issue is due to a **change** in ``ports``. You are trying to access port ``44355`` from port ``3000``. For development, if you are running **windows** run this command ``chrome.exe --disable-site-isolation-trials --disable-web-security --user-data-dir="D:\temp"`` or for **linux** ``nohup google-chrome --disable-web-security --user-data-dir='/tmp' &`` For porduction you need to set header for access different ports. – Not A Bot Mar 12 '20 at 08:29

2 Answers2

3

It doesn't matter what Access-Control-Allow-Origin header you set (at this stage). Read the error message:

It does not have HTTP ok status.

Probably you are responding to the preflight OPTIONS request with a 401 Unauthorized response. This is a problem because the point of the preflight request is to ask permission to make the GET request with the credentials in it.

You need to exclude OPTIONS requests from the authentication rules on your server.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
1

Turns out I'd missed calling app.UseCors(); in startup.cs and was setting the wrong API Key from Cognito in the call header.

Paul Grenyer
  • 1,381
  • 3
  • 21
  • 44