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}`);
    }
}
2
  • 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 and another answer for the same issue here Commented May 20, 2022 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. Commented May 25, 2022 at 7:52

1 Answer 1

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);
        // ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.