How to fetch and display data from Express API to a React app?

Viewed 6143

I have recently started learning react an I am trying to create an application which makes use of an API which I created using Express.

Currently I am hosting my Express API locally at http://localhost:3000/api

However, when i open postman or my browser and send a GET request to http://localhost:3000/api/tasks I get all the tasks that are on my API, as expected.

My react application looks like this

class App extends React.Component{
  constructor(){
    super()
    this.state = {
      tasks: {}
    }
  }
...
  componentDidMount() {
     this.setState({loading: true})
     fetch("http://localhost:3000/api/tasks/1")
       .then(response => response.json())
       .then(data => {
         this.setState({
           tasks: data
         })
       })
   }
...
  render() {
    return(
      <div>
        <p>{this.state.tasks.id}</p>
      </div>
  }
}

When I open the dev tab in my browser I can see that the request (code: 304) is sent and there is a response which is a json file with the object I need. Nevertheless, I am unable to display the data I fetch from the API.

3 Answers

The problem was that the CORS was not enabled! After adding:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    next();
});

to my index.js file of the Express API I was able to fetch and display the data from the API to the react application.

There is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.

(npm cors)

I can give you my sample code since it is hard to see error from your code without debugging.

I am using Nextjs and here is how I get data from server side by using fetch method.

const SamplePage = props => {
    // you can get data from api here from props.data

    const [ testState, setTestState] = useState({
        test: props.data,
    });


    return (
        ...
    )
}

SamplePage.getInitialProps = async ctx => {
    try {
        const { token, username } = nextCookie(ctx);
        const apiUrl = getHost(ctx.req) + `/api/portfolio/${ctx.query.id}`;
        const response = await fetch(apiUrl, {
            method: 'GET',
            headers: {
                Authorization: JSON.stringify({ token, username })
            }
        });

        if (response.ok) {
            const data = await response.json();
            return { data };
        } else {
            // add your action when response is not ok
        }
    } catch (error) {
        // add your action when have error
    }
};

export default withAuthSync(SamplePage);
Related