How to How to fix "No 'Access-Control-Allow-Origin' header is present on the requested resource" in post call in reactJS using Fetch method

13,971

If your client application (the React web app) is on another scheme (any of http/https, domain or port is different), you need to have CORS enabled on your ASP.NET Core back-end.

In the Startup.cs file, you need to add this:

In ConfigureServices()

services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder =>
            {
                builder.WithOrigins("http://localhost:3000/")
                .AllowAnyMethod()
                .AllowAnyHeader();
            });
        });

In Configure() put this just before app.UseMvc():

 app.UseCors();

Check this link for more info: https://docs.microsoft.com/en-us/aspnet/core/security/cors

Share:
13,971

Related videos on Youtube

michealraja d
Author by

michealraja d

Updated on June 04, 2022

Comments

  • michealraja d
    michealraja d almost 2 years

    Getting below error while i call DotNet core API method from ReactJS post call using Fetch options.

    • ReactJS post call only i am getting this error, below way i was tried.

      • Jquery get/post request - working fine
      • Postman get/post request - working fine
      • Swagger get/post request - working fine
      • ReactJS get request - working fine
      • ReactJS post request - Not working fine

    "Access to fetch at 'https://localhost:44352/api/Address/CheckAvailability' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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."

    /*ReactJS Code: */
    
    export function saveAddress(address) {
       return fetch(baseURL + "Address/CheckAvailability", {
        method: "POST",
        headers: {
          "Access-Control-Allow-Origin": "*",
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(address),
      }).then(handleResponse)
        .catch(handleError);
    }
    
    
    /*Dot.Net core Code: */
    [HttpPost]
    public ActionResult CheckAvailability([FromBody]ReqAddressDetailsDto request)
    {
    
      if ((request) == null)
        {
          return NotFound();
        }
      return Ok(request);
    }
  • michealraja d
    michealraja d over 4 years
    Yes, i did what u mentioned. but still not working.
  • michealraja d
    michealraja d over 4 years
    Yes, i did what u mentioned. but still not working.
  • michealraja d
    michealraja d over 4 years
    Yes, i did what u mentioned. but still not working.
  • marcodt89
    marcodt89 over 4 years
    I don't know if browser could complain on header "Access-Control-Allow-Origin": "*" in the request
  • michealraja d
    michealraja d over 4 years
    Might be and i tried last three days, i can't solve this issues. could you tell, whether this issues generated from API or client side API Call
  • marcodt89
    marcodt89 over 4 years
    In my experience, when I had this problem it was only related to server-side. For some reason. Maybe, if you did not do already, try to put "*" (all origins) instead of "http://localhost:3000" to see if it works.
  • marcodt89
    marcodt89 over 4 years
    I mean using builder.AllowAnyOrigin() instead of builder.withOrigins
  • d00lar
    d00lar over 4 years
    what browser ? firefox? try other - firefox like sometimes to throw this error when error is diffrent. also try disable proxy if you have it enabled / configured in system, what is server of this api? iis? does you have enabled anonymous authentication ?
  • jspinella
    jspinella over 4 years
    Works perfectly with .NET Core 3.1 Web API