0

I'm trying to fetch from randomuser.me, my component is:

import React, { Component } from 'react';

class RandomUser extends Component {
    state = {
        contacts:[]
    }

    async   componentDidMount(){
        const url = 'http://api.randomuser.me?results=20';
        const response = await fetch(url, {mode: 'cors'});
        const data = await response.json();
        console.log(data);
    }

    render(){
    console.log(this.state.contacts);
        return (
            <div>
                <h2>Users:</h2>
            </div>
            )
    }
}

export default RandomUser;

The error I see in console is:

enter image description here

Access to fetch at 'http://api.randomuser.me/?results=20' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

How do I correct it? I'm not using any local server and relying on randomuser.me

Please help.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Somename
  • 3,376
  • 16
  • 42
  • 84

1 Answers1

-1

Try it without setting the mode in the fetch. I also have a React project using the randomuser API, I just await fetch(url) and that has always worked.

James South
  • 534
  • 4
  • 15
  • @Quentin `function postData(url = '', data = {}) { // Default options are marked with * return fetch(url, { method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, cors, *same-origin...` from https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options – James South Aug 11 '19 at 18:53
  • @Quentin also working here https://jamessouth.github.io/directory/ with code `let response = await fetch(url);` – James South Aug 11 '19 at 18:56