.net - 使用 ReactJs 从 LocalHost API 获取数据
问题描述
我用 .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 代码)运行我的项目时,结果是空的,没有获取数据..
有人能帮助我吗 ?
解决方案
推荐阅读
- merge - clickhouse:SYSTEM STOP MERGES 不起作用
- r - 如何在我的 R 包中使用 get0 仅在包命名空间中搜索?
- xamarin - Xamarin 形式的激光扫描解决方案
- reactjs - React Native 和 MobX:useContext 不会将更改重新渲染到屏幕上
- python - 2 个几乎相同的“hello world”Flask 应用程序,1 个有效,1 个返回 404 Not Found
- java - 使用排名数组查找优先级队列的最小/最大元素
- sas - 我的 SAS 代码出现错误,我可以寻求帮助吗?
- c++ - 协程参数的生命周期是多少
- python - Python 使用 geopandas 绘制纬度和经度。Pryproj 异常
- python - 在python中组合数字和字符串列表