2

I was trying to call a REST webservice to fetch data from the database and return a JSON object back to the ReactJS app.When I access the URL from the browser it displays the JSON object but when I try to render the data in the table no content is displayed.

My sample code looks like

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>
        )
    }
}

Is this a problem of asynchronous loading ?

Sven Schoenung
  • 30,224
  • 8
  • 65
  • 70
harshal1889
  • 31
  • 1
  • 1
  • 5
  • can you please `console` the data in the `componentDidMount`?what is the data? –  Oct 10 '16 at 06:15
  • Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/users. (Reason: CORS header 'Access-Control-Allow-Origin' missing). This is the console output – harshal1889 Oct 10 '16 at 06:20
  • which server side language are you using? if it is nodejs and express use https://npmjs.org/package/cors package – Lionel Dcosta Oct 10 '16 at 06:36

3 Answers3

1

@Alireza: Thanks for the help. I'm able to fetch the JSON object from the service which currently looks like

{
  "_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"
    }
  }
}

I have used Spring Data Rest for web service implementation and understand that the hypermedia headers(HAL) are included in the json object.Is there any way to ignore these header data while rendering in the react app? Currently the JSON object throws an error at line 2 while parsing.

harshal1889
  • 31
  • 1
  • 1
  • 5
0

According to this question JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on script tags. Note that for JSONP to work, a server must know how to reply with JSONP-formatted results. JSONP does not work with JSON-formatted results.Try to use JSONP in your Ajax call. It will bypass the Same Origin Policy.like this :

  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
        });
    });
    }

Good answer on stackoverflow: jQuery AJAX cross domain

Community
  • 1
  • 1
0

Probably this may be late, but I see an issue with the variable reference to items in your user map method.

Here is your code

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

...

it probably should be

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

...

Note the change in the name of variable in map function from "users" to "user".

deepthought
  • 87
  • 11