【问题标题】:ReactJS Consuming asp.net Rest ServiceReactJS 使用 asp.net Rest 服务
【发布时间】:2018-04-23 21:44:54
【问题描述】:

我对使用 ReactJS 使用 Web 服务 (API) 完全陌生;我有一个带有除用户名和密码之外的登录表单的网页,然后通过单击登录按钮允许用户访问。前端是使用 ReactJS 开发的。

前端代码:

 <form action="">
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
    </div>
    <div class="form-group">
      <label for="pwd">Password:</label>
      <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd">
    </div>
    <div class="form-check">
      <label class="form-check-label">
        <input class="form-check-input" type="checkbox" name="remember"> Remember me
      </label>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>

...我正在使用 Postman 来测试在登录页面后面运行的 Web API Rest 服务。 通过邮递员返回的结果是 { "username": "Jdoe", "firstName": "John", "lastname": "Doe", "password": null, "token:" "ty77fakenumber" }

...我的问题是如何开始将此 API 处理到我的 ReactJS 页面中。是否有我需要实现的 HTTPServiceRequest?任何帮助将不胜感激。

【问题讨论】:

  • 能否请您发布您的反应代码?

标签: reactjs rest api


【解决方案1】:

您可以在 componentDidMount 生命周期方法中使用fetch API 并将结果存储在状态中。

简单 GET 示例:

componentDidMount() {
  fetch(‘/endpoint’)
  .then(res => res.json())
  .then(json => this.setState({users: json)))
}

【讨论】:

  • 这听起来不对。就目前而言,表单只是一个标准的 HTTP POST - 您也需要更改它,不是吗?如果您要使用 fetch,那么您需要将表单作为 POST 正文序列化到请求中。
【解决方案2】:

根据上面的要求,我认为这是指需要向 Rest 服务发出 HTTP 请求以获取结果。我建议使用Fetch API 从 Rest Service 获取数据。这是用于获取数据的异步 HTTP 请求调用。 获得数据后,您还需要一个状态管理框架,您可以在其中存储数据并将其用于组件。在 React 世界中,以下是流行的状态管理框架:

  1. Flux
  2. Redux

当然,你可以在没有这些框架的情况下存储 api 响应,但我假设你会更多地使用 React,一旦你的应用程序变得更大并且越来越多的新组件不断获得,如果没有状态管理框架,状态管理就会变得很麻烦已添加。

【讨论】:

    猜你喜欢
    • 2017-02-18
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多