首页 > 解决方案 > 使用 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 代码)运行我的项目时,结果是空的,没有获取数据..

有人能帮助我吗 ?

标签: .netreactjsapifetch

解决方案


推荐阅读