0

This may be a duplicate question.

I'm using react for frontend and asp.net core Web API for backend. I tried to fetch data using react query but got an error like this.

Access to XMLHttpRequest at 'https://localhost:7036/api/{Controller Name}/{Action}' from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Now, I have seen a similar answer for this error, in this post Access to XMLHttpRequest at '...' from origin 'localhost:3000' has been blocked by CORS policy But, I would like to know is there any standard or superior way to solve this using react query ?

Controller and Action

[Route("api/[controller]")]
[ApiController]
  public class GeneralController : ControllerBase {

       public JsonResult GetMatureVerifyData() // Action Method
         {
            using(var model = new MatureVerifiedDataDTO()){

                  return new JsonResult(model);

                }
          }
  }

React Query Code

import axios from "axios";
import { useQuery } from "react-query";

export const APIcall = () => {
    const { isLoading, error, } = useQuery("verify", () =>
         axios.get(
            "https://localhost:7036/api/General/GetMatureVerifyData"
        ).then((res) => console.log(res.data))
    );

    if (isLoading) {
        console.log("Loading...");
    };

    if (error) {
        console.log(`An error has occurred: ${error.message}`);
    }
}
  • CORS policy block errors are mainly due to your configuration in the server side program. There're limit to almost nothing you can do on the front end side for CORS policy error besides enable it on your server. You can read more on the policy [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors) and another answer for the same issue [here](https://stackoverflow.com/a/70512005/5972355) – Tung Pham May 20 '22 at 20:15
  • react-query doesn't know / care about how the result is produced - it only accepts a Promise from the queryFn, which could also be created with `() => Promise.resolve(5)`. So no, there is nothing react-query per se can do here. – TkDodo May 25 '22 at 07:52

1 Answers1

1

This is not a react issue. This is a security measure implemented by browsers. You need to enable cors in your asp.net web api project to allow https://localhost:3000.

WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
   config.EnableCors();
}

Next, add the [EnableCors] attribute to the Controller class:

[EnableCors(origins: "https://localhost:3000", headers: "*", methods: "*")]
public class GeneralController : ControllerBase {

You can also skip step 2 & enable it globally for all Web API controllers in your application.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("https://localhost:3000", "*", "*");
        config.EnableCors(cors);
        // ...
    }
}
A G
  • 21,087
  • 11
  • 87
  • 112