I created an API with .Net API and I tested it with Postman and results show up perfectly. Now I'm trying to get data from this local API in my react js application so I tried this code :
import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch("http://localhost:51492/api/user/1")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} {item.prenom}
</li>
))}
</ul>
);
}
}
}
MyComponent.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles()(MyComponent);
The link of my API is : http://localhost:51492/api/user/1
The result when I run my project with npm start
(using Visual Studio Code) is empty, no data fetched ..
Can someone help me please?