Basically I am trying to find a way how the fetch data works. I have created a method that returns a simple list and the response of the body is as follow:
[
{
"Name": "ApooBG",
"Password": "e062f192A",
"Email": "[email protected]"
},
{
"Name": "VenszBG",
"Password": "12645",
"Email": "[email protected]"
},
{
"Name": "PetarGH",
"Password": "1245",
"Email": "[email protected]"
}
]
then I have in react a button that calls a method, where it should get this list.
<div> <button onClick={Testing}>Edit Info</button></div>
const Testing = () => {
fetch("https://localhost:7101/GetUsers")
.then((response) => response.json())
.then((data) => {
console.log(data);
})
};
When I try to click on the button I need to get the users in the console.log but instead I get
Could you guys tell me what I am doing wrong as I really don't get the idea. The url should be okay as this is what the request URL is. Therefore, the problem should be somewhere else.
CodePudding user response:
I don't know if it will help, how about testing with dummy API first available online? Here one of open API example that can be used:
const Example = ({title}) => {
const Testing = () => {
fetch("https://dummyjson.com/users/1")
.then((response) => response.json())
.then((data) => {
console.log(data);
})
};
return (
<div>
<p>{title}</p>
<button onClick={Testing}> Edit Info</button>
</div>
);
};
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render(
<Example title="Example:" />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
If this work, try to check your backend port and proxy setting. Maybe this one will help https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022
CodePudding user response:
I just check the log. TypeError: Failed to fetch
might occurs when the API Cross-Origin Resource Sharing (CORS) errors happen. Check out this answer https://stackoverflow.com/a/49895164/10766263