Home > front end >  Fetch() GET request in reactjs throwing error
Fetch() GET request in reactjs throwing error

Time:10-18

 import React, { Component } from 'react'


export default class Games extends Component {
state ={
    loading: true,
    
    
    
}
   async componentDidMount(){
   
    const url="https://api.steampowered.com/ISteamApps/GetAppList/v0001/";
    const response = await fetch(url);
    const data= await response.json();
    this.setState({game: data.applist[0],loading:false});
    
}
render() {
    return (
        <div>
            {this.state.loading||!this.state.game?(<div>loading...</div> ):(
            <div>
                <div>{this.state.game.appid}</div>
                <div>{this.state.game.name}</div>
            </div>)}
        </div>
    );
}
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Access to fetch at 'https://api.steampowered.com/ISteamApps/GetAppList/v0001/' 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. Games.js:14 GET https://api.steampowered.com/ISteamApps/GetAppList/v0001/ net::ERR_FAILED

CodePudding user response:

This isn't a react specific bug. Let me explain what's happening here.

Simplified explanation to CORS: (more here)

CORS is the mechanism which allows the server to send a response back for an api (in your case url=https://api.steampowered.com/ISteamApps/GetAppList/v0001/) only when the request is coming from a specific domain/origin.

For example using CORS we can allow server to respond only to API Requests made from www.steampowered.com origin. (and not localhost and other origins)

Now coming to:

If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled

This means that you can still get the response but of type opaque. Run this and see the response:

async function apiCall() {
    const url = 'https://api.steampowered.com/ISteamApps/GetAppList/v0001/'
    const response = await fetch(url, {
        mode: 'no-cors',
    })
    console.log(response)
}

try {
    apiCall()
} catch (e) {
    console.log('Err is', e.message)
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

From developers.google.com:

An opaque response is for a request made for a resource on a different origin that doesn't return CORS headers. With an opaque response we won't be able to read the data returned or view the status of the request, meaning we can't check if the request was successful or not.

You can use proxies to bypass this. Although if you own the aforementioned url, you can configure to grant yourself the necessary access.

  • Related