【问题标题】:Calling a REST webservice from ReactJS从 ReactJS 调用 REST Web 服务
【发布时间】:2017-02-18 12:20:24
【问题描述】:

我试图调用 REST Web 服务从数据库中获取数据并将 JSON 对象返回给 ReactJS 应用程序。当我从浏览器访问 URL 时,它会显示 JSON 对象,但是当我尝试在其中呈现数据时表格没有内容显示。

我的示例代码如下所示

import React from 'react';
import $ from 'jquery'; 

export default class Members extends React.Component {
  constructor(props) {
    super(props);
    this.state = { users: [] };
  }

  componentDidMount() {
    $.ajax({
      url: "http://localhost:8080/users"
    }).then(function(data) {
        this.setState({
                    users:data
        });
    });
    }
  render() {
    return (
     <UsersList users={this.state.users}/>
    )
  }
}

class UsersList extends React.Component {
    render() {
        var users = this.props.users.map(users =>
            <User key={user._links.self.href} user={user}/>
        );
        return (
            <table>
                <tbody>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                    </tr>
                    {users}
                </tbody>
            </table>
        )
    }
}
class User extends React.Component {
    render() {
        return (
            <tr>
                <td>{this.props.user.firstName}</td>
                <td>{this.props.user.lastName}</td>
            </tr>
        )
    }
}

这是异步加载的问题吗?

【问题讨论】:

  • 请问consolecomponentDidMount中的数据是什么?数据是什么?
  • 跨源请求被阻止:同源策略不允许读取localhost:8080/users 的远程资源。 (原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。这是控制台输出
  • 您使用哪种服务器端语言?如果是 nodejs 和 express 使用 npmjs.org/package/cors

标签: json web-services rest reactjs


【解决方案1】:

这可能会迟到,但我发现您的用户映射方法中对项目的变量引用存在问题。

这是你的代码

class UsersList extends React.Component {
  render() {
    var users = this.props.users.map(users =>
   <User key={user._links.self.href} user={user}/>
);

...

应该是这样的

class UsersList extends React.Component {
  render() {
    var users = this.props.users.map(user =>
   <User key={user._links.self.href} user={user}/>
);

...

注意map函数中变量名从“users”改为“user”。

【讨论】:

    【解决方案2】:

    @Alireza:感谢您的帮助。 我能够从当前看起来像

    的服务中获取 JSON 对象
    {
      "_embedded" : {
        "users" : [ {
          "firstName" : "Harshal",
          "lastName" : "Patil",
          "location" : "ABC",
          "userId" : "USR_1",
          "_links" : {
            "self" : {
              "href" : "#urlLink"
            },
            "user" : {
              "href" : "#urlLink"
            }
          }
        } ]
      },
      "_links" : {
        "self" : {
          "href" : "#urlLink"
        },
        "profile" : {
          "href" : "#urlLink"
        }
      }
    }
    

    我已经使用 Spring Data Rest 进行 Web 服务实现,并且了解超媒体标头 (HAL) 包含在 json 对象中。在 React 应用程序中呈现时,有什么方法可以忽略这些标头数据? 目前 JSON 对象在解析时在第 2 行抛出错误。

    【讨论】:

      【解决方案3】:

      根据this 问题,JSONP 或“带填充的 JSON”是一种在 Web 浏览器中运行的 JavaScript 程序中使用的通信技术,用于从不同域中的服务器请求数据,这是典型的 Web 浏览器所禁止的,因为相同 -原产地政策。 JSONP 利用了浏览器不对脚本标签强制执行同源策略这一事实。请注意,要使 JSONP 工作,服务器必须知道如何使用 JSONP 格式的结果进行回复。 JSONP 不适用于 JSON 格式的结果。尝试在 Ajax 调用中使用 JSONP。它将绕过同源策略。像这样:

        componentDidMount() {
          $.ajax({
            url: "http://localhost:8080/users",
            async:true,
            dataType : 'jsonp'   //you may use jsonp for cross origin request
            crossDomain:true,
          }).then(function(data) {
              this.setState({
                          users:data
              });
          });
          }
      

      stackoverflow 上的好答案:jQuery AJAX cross domain

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-04
        • 1970-01-01
        • 2016-08-26
        • 2013-01-14
        • 2015-03-17
        • 1970-01-01
        • 1970-01-01
        • 2015-04-25
        相关资源
        最近更新 更多