Fetch request to local file not working

I'm trying to make a request in a local file, but I don't know when I try to do on my computer show me an error. Is possible make a fetch to a file inside your project?

 // Option 1
 componentDidMount() {
     fetch('./movies.json')
     .then(res => res.json())
     .then((data) => {
        console.log(data)
     });
 }

 error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 -->  .then(res => res.json())

 // Option 2
 componentDidMount() {
    fetch('./movies.json', {
       headers : { 
         'Content-Type': 'application/json',
         'Accept': 'application/json'
       }
    })
   .then( res => res.json())
   .then((data) => {
        console.log(data);
   });
 }

 error1: GET http://localhost:3000/movies.json 404 (Not Found) at App.js:15 --> fetch('./movies.json', {
 error2: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 -->  .then(res => res.json())


 // This works
 componentDidMount() {
   fetch('https://facebook.github.io/react-native/movies.json')
   .then( res => res.json() )
   .then( (data) => {
      console.log(data)
   })
 }

Answers 1

  • Your JSON file needs to be served by the server so you need the express server (or any other). In this example we are using using express.

    Note: you can also download git repo

    App.js File

    import React, { Component } from 'react';
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          data: null
        };
      }
    
      componentDidMount() {
        const myHeaders = new Headers({
          "Content-Type": "application/json",
          Accept: "application/json"
        });
    
        fetch("http://localhost:5000/movie", {
          headers: myHeaders,
    
        })
          .then(response => {
            console.log(response);
            return response.json();
          })
          .then(data => {
            console.log(data);
            this.setState({ data });
          });
      }
    
      render() {
        return <div className="App">{JSON.stringify(this.state.data)}</div>;
      }
    }
    
    export default App;
    

    server.js

    var express = require("express");
    var data = require('./movie.json'); // your json file path
    var app = express();
    
    
    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");
      next();
    });
    
    app.get("/movie", function(req, res, next) {
      res.send(data);
    });
    
    app.listen(5000, () => console.log('Example app listening on port 5000!'))
    

Related Articles