Skip to content
Advertisement

Fetch JSON file from url in Javascript, React Native

I have a problem fetching JSON data from url. I would really appreciate it if you could help me solve this issue.

I wanted to fetch JSON data from firebase storage, but somewhat I can’t, so I simplified the code and now it’s really simple, but no luck. I also searched the cause of the error in this community, but I didn’t find it.

This is my code.

import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';

export default class App extends Component {
  render() {
    return (
      <View>
        <TouchableOpacity onPress={this.handleOnPress}>
          <Text>test</Text>
        </TouchableOpacity>
      </View>
    );
  }
  handleOnPress = () => {
    console.log('test was clicked');
    fetch('https://facebook.github.io/react-native/movies.json')
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));
  };
}

needless to say, the message, ‘test was clicked’ is displayed without any problem

Error message

Error: "Failed to fetch" in TypeError: Failed to fetch ...

I use Expo Snack, web compiler.

Thank you.

Advertisement

Answer

Is the error before Failed to fetch: Access to fetch at 'https://facebook.github.io/react-native/movies.json' from origin 'XXX' 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.

If so, it is a CORS issue.

If not, feel free to post any other information you are seeing. I’m sure there must be more errors logged than – Failed to Fetch.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement