4

I try hard to fetch data from external API within a React-App. But it always gives me the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://api.example.com' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

This is my code:

// @flow

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

const URL = 'http://api.example.com/my/api/request' // obfuscated

class App extends Component {

  componentDidMount() {
    fetch(URL).then( response => {
      console.log(response);
    })  
    .catch(err => {
      console.log(err);
    })
  }

  render() {
    return (
      <div className="App">
      <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small>
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React!</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

As far as i know the CORS-thing is only required on client-side requests, not for server-side requests.

Who can help me?

2 Answers 2

1

componentDidMount hook will never be called on the server side. As a result, your fetch code is only running in the browser after an application has been mounted into your DOM. To fetch data from the server you can use fetch inside componentWillMount hook, it will be called on the server, but on the client too.

Sign up to request clarification or add additional context in comments.

Comments

0

You have to call api request on the server, wait for the response and return rendered html page.

I have created a starter for server-side rendering https://github.com/gzoreslav/react-redux-saga-universal-application

It uses redux and redux-saga

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.