-2

I have the following controller in web-api, and I am working using React v18.2.0 and NextJS v13.3.0:

        public List<ReturnDat> Get()
    {
        List<ReturnDat> lst = new List<ReturnDat>();

        lst.Add(new ReturnDat() { 
        ID = 1,
        Title = "Title -1 "
        });

        return lst;
    }

and the following class:

     public class ReturnDat
    {
        [DataMember(EmitDefaultValue = false)]
        public int ID { get; set; }

        [DataMember(EmitDefaultValue = false)]
        public string Title { get; set; }
    }

And this is the WebApiConfig.cs

               config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
.Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept",
                              "text/html",
                              StringComparison.InvariantCultureIgnoreCase,
                              true,
                              "application/json"));

React:

 const[data,setData] = useState([]);
  const[num,setNum] = useState(1);
  
  const fetchData = async () => {
    const response = await fetch("https://localhost:44346/api/values/");
    //https://swapi.dev/api/people/1/
    const newData = await response.json();

  };
  
useEffect(() =>{



  fetchData();});

The problem is that the API getting hit and it arrives to the return statement, however from the React side it says: TypeError: Failed to fetch.

With the same code I tried this API (I found it on the net, not done by me) https://swapi.dev/api/people/1/ and the code works fine! So I am suspecting that I need to do some config to my API , so I tried

  1. to add and remove the [DataMember]
  2. Add and remove JSON formatting in the config file of the web api.
  3. Changed the return type.

Nothing worked!

Then I used the NextJS getServerSideProps(), and the data was returned from the API.

What could be the problem and how to solve it?

This is what being returned in the network tab: enter image description here

Hasan Shouman
  • 2,162
  • 1
  • 20
  • 26
  • 1
    @HasanShouman: The picture shown pretty strongly implies a CORS problem. When you dismiss the details of the specific request, what information is shown about the two "red" requests? On the console tab, what exact information is shown? Is there perhaps something about a pre-flight check or `OPTIONS` request which is failing the same-origin policy? If so then you'd need to enable and configure CORS on the server-side code to allow cross-origin requests from this client. – David Apr 20 '23 at 12:57

1 Answers1

-1

Note that useEffect can be used for client-side rendering (CSR) while getServerSideProps is used for server-side rendering (SSR), these are two different approaches to data fetching in Next.js.

The error is likely related to Access-Control-Allow-Origin or other CORS configuration in your backend application.

mimak
  • 211
  • 2
  • 9
  • How can I know? And why it is working when using getServerSideProp – Hasan Shouman Apr 20 '23 at 12:44
  • 1
    @HasanShouman When using getServerSideProps, the data is fetched by the Next.js server rather than by the browser, which results in different values being put in access headers like Access-Control-Allow-Origin, please inspect your request's headers and compare them when using both of your solutions – mimak Apr 20 '23 at 12:54
  • 1
    @mimak how does that answer the question? You are guessing that it's CORS which *may* be correct but isn't necessarily so. We expect answers to the question to be definitive: put guesses in the comments. The only thing else in your "answer" is a bunch links to things that the question implies the OP is already aware of. – Jared Smith Apr 20 '23 at 13:06
  • I dont know why this question was closed. All the code details was provided and the result was provided, but someone decided that this question is lacking code! – Hasan Shouman Apr 22 '23 at 13:50