我用.Net Api创建了一个API 我用Postman进行了测试,结果显示得很完美 现在我正在尝试从我的react js应用程序中的本地api获取数据 所以我尝试了这段代码:
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);
我的API的链接是:http://localhost:51492/api/user/1
当我使用npm start运行项目(使用Visual Studio代码)时,结果为空,没有获取数据..
有人可以帮我吗?