0

I created an API with .Net API and I tested it with Postman and results show up perfectly. Now I'm trying to get data from this local API in my react js application so I tried this code :

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

The link of my API is : http://localhost:51492/api/user/1

The result when I run my project with npm start (using Visual Studio Code) is empty, no data fetched ..

Can someone help me please?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Maryem Samet
  • 133
  • 1
  • 5
  • 23
  • 1
    What do you get if you open up the Network tab in your Developer Tools? Since `http://localhost:51492` most likely is another origin, you must enable CORS in your API. – Tholle Aug 11 '18 at 22:03
  • So, have you solved your CORS (probable) issue then? https://stackoverflow.com/questions/51749624/fetching-data-from-api-in-react-js-failed We don't know that since you did not give any feedback in your other answer. – devserkan Aug 11 '18 at 22:03
  • @Tholle when i open http://localhost:51492/api/user/1 i get Json format .. like what i got in PostMan .. – Maryem Samet Aug 11 '18 at 22:09
  • @devserkan hey , i'm sorry for not replying , i just couldn't understand how to fix the issue ,i just make it work in localhost instead of working with CodeSandBox , i thought that was the issu with fixing data from local API , but i think there is another issue . i'm sorry again for not replying – Maryem Samet Aug 11 '18 at 22:11
  • Yes, if you open it up in the address bar it will work, but what happens when you send the request from your app is what is interesting. If you open up your Developer Tools and check the Network tab, what error do you get? – Tholle Aug 11 '18 at 22:11
  • @Tholle i get that : Failed to load http://127.0.0.1:51492/api/user/1: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. – Maryem Samet Aug 11 '18 at 22:15
  • Great! That tells you black and white that it's a CORS issue. You can Google how to activate CORS for your particular server technology. – Tholle Aug 11 '18 at 22:15
  • 2
    thanks for both of u , i'll look for activating CORS in Google , since i'm new in react js and this is my first time trying to get data from an api .. so i couldn't understand what's happening . thank u – Maryem Samet Aug 11 '18 at 22:20
  • It is better to get a feedback but no problem about that. If you are using CRA or Webpack you can use a proxy on your localhost. This is the easiest way of doing this. But for production, I think you need to configure your server for CORS. – devserkan Aug 11 '18 at 22:33
  • i don't use CRA or Webpack , and i'm developping an application as part of my internship . so i'm trying to configure my IIS Express .. i don't get the problem fixed too .. i'm following this http://www.melvinswebstuff.com/blog/2015/01/02/enable-cors-iisexpress/ – Maryem Samet Aug 11 '18 at 23:01

0 Answers0