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
- to add and remove the [DataMember]
- Add and remove JSON formatting in the config file of the web api.
- 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?