ERORR when fetching POST method in React Native to ASP.NET

daowdos 261 Reputation points
2022-10-03T05:43:10.063+00:00

Hi, I have an error with - fetch that been blocked "by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers" .

Each method as GET, POST makes an error, but due to different requests.
Now I really don't know why is this happening and I worked for hours to search that cause and solution, it's the same error as I had with e GET but needs different changes which I don't know what (frustrating)
I tried many changes for the POST function below but didn't worked!

Games.js

    const postResulttoDB = async () => {   
    let gameData = {   
      user1: gameResult.p1,   
      user2: gameResult.p2,   
    };   
    try {   
       const fetchResponse = await fetch(URL, {   
        method: 'POST',   
        headers: {   
           'Content-type': 'application/json; charset=UTF-8',   
        },   
        body: JSON.stringify(gameData)   
      });   
      const data = await fetchResponse.json();   
      return data;   
    } catch (err) {   
      return console.log('error catch', err);   
    }   

Program.cs - GET method function is working with this code

var _Policy1 = "Policy1";    
var builder = WebApplication.CreateBuilder(args);   
   
builder.Services.AddCors(options =>   
{   
    options.AddPolicy(name: _Policy1,   
    policy =>   
    {   
        policy.WithOrigins("http://example.com",   
                            "http://www.contoso.com",   
                            "http://localhost:19008",   
                             "http://localhost:19009").AllowAnyMethod();    
    });       
});   
       
builder.Services.AddControllers();   
builder.Services.AddEndpointsApiExplorer();   
builder.Services.AddSwaggerGen();   
   
var app = builder.Build();   
   
 if (app.Environment.IsDevelopment())   
{   
    app.UseSwagger();   
    app.UseSwaggerUI();   
}   
   
app.UseHttpsRedirection();   
app.UseStaticFiles();   
app.UseRouting();   
app.UseCors(_Policy1);      
app.UseAuthorization();   
app.MapControllers();   
app.Run();   

Access to fetch at 'http://www.whatywant.com/api/SetGameResults' from origin 'http://localhost:19008' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
POST http://www.whatywant.com/api/SetGameResults net::ERR_FAILED

Addition

With that I get no error but still no data is being passed to the Database, I see no error -
js

 body: JSON.stringify(gameData),  
   method: 'POST',  
 headers: {  
   Accept: 'application/json',  
     'Content-type': 'application/json; charset=UTF-8',  
    },  

cs

  options.AddPolicy("PolicyPOST",  
        policy =>  
        {  
            policy.WithOrigins("http://example.com",  
                                "http://www.contoso.com",  
                                "http://localhost:19008",  
                                 "http://localhost:19009").AllowAnyHeader()  
                                 .AllowAnyMethod()  
                                 .AllowCredentials();  

I'm glad we have the Q&A here so wonderful people can help.
Thanks in advance!

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,164 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,552 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 55,686 Reputation points
    2022-10-03T20:39:13.84+00:00

    the error says you are using custom headers (Content-type), but your CORS policy does not allow custom headers. add

    .AllowAnyHeader()


2 additional answers

Sort by: Most helpful
  1. Lan Huang-MSFT 25,551 Reputation points Microsoft Vendor
    2022-10-03T07:05:21.207+00:00

    Hi @daowdos ,
    Microsoft documentation states that if you want to use JavaScript to access resources on the server, then you must call app.UseCors() before app.UseStaticFiles().
    https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0#usecors-and-usestaticfiles-order

    > Typically, UseStaticFiles is called before UseCors. Apps that use JavaScript to retrieve static files cross site must call UseCors before UseStaticFiles.

    app.UseHttpsRedirection();  
    app.UseCors(_Policy1);   // This should be above the UseStaticFiles();  
    app.UseStaticFiles(); //  Below the UseCors();  
    

    Best regards,
    Lan Huang


    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.


  2. Bruce (SqlWork.com) 55,686 Reputation points
    2022-10-03T20:14:54.53+00:00

    CORS configuration and coding is server side only. The browser implements the client side. the npm CORS modules are for node based web servers (connect/express).

    the asp.net min api configures app.UseEndpoints() automatically.

    0 comments No comments