Access to fetch been blocked by CORS policy - React Native + ASP.net Core App

daowdos 261 Reputation points
2022-09-28T08:02:14.317+00:00

Hi,
I understand what's Cross-Origin Requests error I'm getting and why it is important.
So I tried to enable then to disable CORS and to Enable CORS in my project with the explanations in docs -
cors

But nothing does it, in chrome I get the same error (except when I change mode to 'no-cors')**

Access to fetch at 'https://localhost:40011/api/Games/GamesList' from origin 'http://localhost:19008' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

App.js

 return fetch('https://localhost:40011/api/Games/GamesList', {    
      method: 'GET',    
      withCredentials: true,    
      crossorigin: true,    
      mode: 'no-cors',       
    })    
      .then((res) => res.json())    
      .then((data) => {    
        console.log(data);    
      })    
      .catch((error) => {    
        console.error(error);    
      });    
  };    

Also tried with -
headers: {
'Access-Control-Allow-Origin': '*',
},

When mode: 'no-cors' I get only this error -

bundle.js:47575 SyntaxError: Unexpected end of input (at bundle.js:898:18)
at bundle.js:898:18

I know this has been asked many times before in the web, but I tried and read many things, some just ruin the project in React - I had to delete files and reinstall, besides that nothing helped.

Will be glad to understand what should I do and why these doesn't work.

Thanks in advanced.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,127 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
291 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,006 Reputation points Microsoft Vendor
    2022-09-28T10:56:45.397+00:00

    Hi @daowdos ,

    bundle.js:47575 SyntaxError: Unexpected end of input (at bundle.js:898:18)

    This issue relate the 'no-cors' mode. Try to remove it.

    Access to fetch at 'https://localhost:40011/api/Games/GamesList' from origin 'http://localhost:19008' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

    For this issue, you need to configure the API application to allow the origin http://localhost:19008.

    Code like this:

    var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";  
      
    var builder = WebApplication.CreateBuilder(args);  
      
    builder.Services.AddCors(options =>  
    {  
        options.AddPolicy(name: MyAllowSpecificOrigins,  
                          policy  =>  
                          {  
                              policy.WithOrigins("http://localhost:19008",  
                                                  "http://www.contoso.com"); // add the allowed origins  
                          });  
    });  
      
    // services.AddResponseCaching();  
      
    builder.Services.AddControllers();  
      
    var app = builder.Build();  
    app.UseHttpsRedirection();  
    app.UseStaticFiles();  
    app.UseRouting();  
      
    app.UseCors(MyAllowSpecificOrigins);  
    

    More detail information, see Enable Cross-Origin Requests (CORS) in ASP.NET Core.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    3 people found this answer helpful.

3 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 54,621 Reputation points
    2022-09-28T16:11:00.077+00:00

    in react native the requests are not blocked by CORS. also with react native, https://localhost is the mobile device (or emulator) which typically would not have web server support.

    are you sure you are coding in react native?

    if you are using browser hosted react, then use the static file handler and have the webapi host the react app, and CORS will not be required. for development have the react dev server proxy to the webapi so CORS is not required.

    1 person found this answer helpful.

  2. Laxmikant 216 Reputation points
    2022-09-28T18:22:00.217+00:00

    define CORS policy in program.cs

    builder.Services.AddCors(options =>  
        {  
          
        options.AddDefaultPolicy(  
            policy =>  
            {  
                policy.WithOrigins("http://localhost:19008")  
                    .AllowAnyHeader()  
                    .AllowAnyMethod();  
            });  
    });  
    
    var app = builder.Build();  
    app.UseCors();  
    

    for more details on CORS - https://geeksarray.com/blog/how-to-setup-cors-policies-in-aspnet-core-web-api

    1 person found this answer helpful.

  3. Bruce (SqlWork.com) 54,621 Reputation points
    2022-09-29T20:40:24.137+00:00

    you can only accurately get the port after app.StartAsync(), which is too late for configuring CORS. your best bet is to add a setting for the CORS port in your appsettings.json