Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

javascript - 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)
   })
 }
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are trying to serve a static file with a fetch command, which inherently requires the file to be served by a server. To resolve the issue, you have a few options available to you. I am going to outline the two that are most commonly suggested for such a thing:

  • Use Node.js and something like expressjs to host your own server that serves the file you want to fetch. While this procedure might require more effort and time, it is certainly more customizable and a good way to learn and understand how fetching from a backend works.
  • Use something like Chrome Web Server to easily set up a very simple server to serve your file on your local network. Using this method, you have very little control over what you can do with said web server, but you can quickly and easily prototype your web application. However, I doubt there's a way to move this method to production.

Finally, there are other options where you can upload one or more files online and fetch them from an external URL, however this might not be the optimal strategy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...