获取本地文件的请求不起作用 [英] Fetch request to local file not working

查看:156
本文介绍了获取本地文件的请求不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在本地文件中发出请求,但我不知道我何时尝试在计算机上显示错误。是否可以获取项目中的文件?

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)
   })
 }


推荐答案

你正在尝试使用fetch命令提供静态文件,这本身就要求服务器提供文件。要解决这个问题,你可以选择一些选项。我将概述最常用的两个选项。一件事:

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:


  • 使用Node.js和 expressjs 用于托管您自己的服务器,该服务器提供您要获取的文件。虽然此过程可能需要更多的努力和时间,但我t当然可以更加自定义,也是了解和了解后端提取方式的好方法。

  • 使用类似 Chrome Web Server 可以轻松设置一个非常简单的服务器来为您的本地网络上的文件提供服务。使用此方法,您几乎无法控制使用所述Web服务器可以执行的操作,但您可以快速轻松地对Web应用程序进行原型设计。但是,我怀疑是否有办法将此方法转移到生产中。

  • 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.

最后,还有其他选项可以上传一个或多个在线文件并从外部URL获取它们,但这可能不是最佳策略。

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.

这篇关于获取本地文件的请求不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆