【问题标题】:React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
【发布时间】:2019-08-14 08:10:19
【问题描述】:

我想在 react js 中获取我的 Json 文件,为此我使用fetch。但它显示一个错误

Uncaught (in promise) SyntaxError: Unexpected token &lt; in JSON at position 0

可能是什么错误,我不知道。我什至验证了我的 JSON。

handleGetJson(){
  console.log("inside handleGetJson");
  fetch(`./fr.json`)
    .then((response) => response.json())
    .then((messages) => {console.log("messages");});
}

我的 Json (fr.json)

{
  "greeting1": "(fr)choose an emoticon",
  "addPhoto1": "(fr)add photo",
  "close1": "(fr)close"
}

【问题讨论】:

  • 也许你得到了错误页面的响应,看看开发者工具中的网络标签是什么响应。
  • 是的。我在 fr.json 中得到了一些垃圾 html。
  • 好的,我解决了这个问题。首先需要通过localhost 加载.json。所以我改变了fetch('http://localhost/img/fr.json')。此外,我在 localhost:8080 上运行我的应用程序,因此发生了一个 CORS 问题,通过 chrome 插件禁用它来解决这个问题。无论如何,非常感谢@jcubic 的提醒,因为有时代码中没有任何错误。
  • 检查您正在加载的数据是否为 ​​JSON 格式(“
  • 我正在使用 React 中的 Api,我已将其从 await fetch(https://api.com/search?q=chicken&amp;app_id=${APP_ID}&amp;app_key=${APP_KEY}) 更改为 await fetch(http://localhost:3000/https://api.com/search?q=chicken&amp;app_id=${APP_ID}&amp;app_key=${APP_KEY}),但我仍然收到一条错误消息:“Unexpected token

标签: javascript json ajax reactjs


【解决方案1】:

添加两个标头Content-TypeAccept 等于application/json

handleGetJson(){
  console.log("inside handleGetJson");
  fetch(`./fr.json`, {
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }

    })
    .then((response) => response.json())
    .then((messages) => {console.log("messages");});
}

【讨论】:

  • 这是一个 GET 请求,所以发送 Content-Type 标头是完全错误的。请求中没有描述类型的内容。设置Accept 标头可以解决问题,但很少有服务器实际执行内容协商,因此它不太可能提供帮助。 OP 还明确表示(在对该问题的评论中)他们遇到了 CORS 错误并且使用了错误的 URL,因此不清楚为什么 @iamsaksham 接受这是他们问题的解决方案。
【解决方案2】:

这主要是由您的 React/Client 应用程序中的问题引起的。将此行添加到您的客户package.json 解决它

“代理”:“http://localhost:5000/

注意:将 5000 替换为您的服务器正在运行的端口号

参考:How to get create-react-app to work with a Node.js back-end API

【讨论】:

  • 这没有回答问题。
【解决方案3】:

对我有用的解决方案是:- 我将我的 data.json 文件从 src 移动到公共目录。 然后使用 fetch API 来获取文件。

fetch('./data.json').then(response => {
          console.log(response);
          return response.json();
        }).then(data => {
          // Work with JSON data here
          console.log(data);
        }).catch(err => {
          // Do something for an error here
          console.log("Error Reading data " + err);
        });

问题在于,在编译 react 应用程序后,获取请求会在 URL“http://localhost:3000/data.json”处查找文件,这实际上是我的 react 应用程序的公共目录。但不幸的是,在编译 react app 时 data.json 文件并没有从 src 移动到公共目录。所以我们必须明确地将 data.json 文件从 src 移动到 public 目录。

【讨论】:

  • 这个答案在 react js 上下文中是最合适的。大多数人不检查网络中 json 文件的 404。 json需要在公共目录中
【解决方案4】:

当 API(您正在使用)没有发送相应的 JSON 时,它可能会出现。 您可能会遇到 404 页面或类似 HTML/XML 响应的响应。

【讨论】:

    【解决方案5】:

    我遇到了同样的错误,对我来说,这是因为 API 只是返回一个字符串,但是在 fetch 调用中我期待 json:

    response => response.json()
    

    从 API 返回 json 为我解决了这个问题,如果您的 API 不应该返回 json,那么就不要这样做response.json()

    【讨论】:

      【解决方案6】:

      可以收到此错误,但请注意,这可能是对真正问题的转移注意力。在我的情况下,错误状态中的 JSON 没有问题,而是发生了 404,它无法将 JSON 数据拉到第一个位置进行处理,从而导致此错误。

      对此的修复是,为了在本地项目中的 .json 文件上使用 fetch.json 文件必须是可访问的。这可以通过将其放置在项目根目录中的文件夹中来完成,例如 public 文件夹。一旦我将json文件移动到那个文件夹中,404变成了200,Unexpected token &lt; in JSON at position 0错误就解决了。

      【讨论】:

      • ...这救了我 ;-)
      • 这就是为我解决的问题。我的 src 文件夹中有 JSON。将其移至 public 即可。
      • 这也对我有用。这样做有缺点吗?
      • 对我来说也是红鲱鱼......我的问题是我发送请求的位置。忘记包含 https://
      【解决方案7】:

      关于您的 Promise 响应 你要求

      response.json() 
      

      但是如果您的服务器发送 json 响应作为回报,这会很好用 特别是如果您在服务器端使用 Node Js

      所以再次检查并确保您的服务器发送 json 作为响应 正如所说,如果它的 NodeJS 响应可能是

      res.json(YOUR-DATA-RESPONSE)
      

      【讨论】:

        【解决方案8】:

        我确认这里提出的一些方法也对我有用:您必须将本地 .json 文件放在 fetch() 正在查找的公共目录中(在 http://localhost:3000/ 中查找) 例如:我在我的 src/App.js 文件中使用了这个 fetch()

        componentDidMount(){
          fetch('./data/json-data.json')
          .then ( resp1 => resp1.json() )
          .then ( users1 => this.setState( {cards : users1} ) )
        }
        

        所以我创建了 public/data/json-data.json

        然后一切都很好:)

        【讨论】:

          【解决方案9】:

          我得到了错误。 我只是在 package.json 中添加了“代理”,错误就消失了。 错误就在那里,因为 API 请求是在 react 应用程序运行的同一端口发出的。您需要提供代理,以便对运行后端服务器的端口进行 API 调用。

          【讨论】:

            【解决方案10】:

            有时您的 API 后端无法遵守合同,并发送纯文本(即 Proxy error: Could not proxy request ...&lt;html&gt;&lt;body&gt;NOT FOUND&lt;/body&gt;&lt;/html&gt;)。

            在这种情况下,您需要处理以下两种情况:1) 有效的 json 响应错误,或 2) 文本负载作为后备(当响应负载不是有效的 json 时)。

            我建议这样处理这两种情况:

              // parse response as json, or else as txt
              static consumeResponseBodyAs(response, jsonConsumer, txtConsumer) {
                (async () => {
                  var responseString = await response.text();
                  try{
                    if (responseString && typeof responseString === "string"){
                     var responseParsed = JSON.parse(responseString);
                     if (Api.debug) {
                        console.log("RESPONSE(Json)", responseParsed);
                     }
                     return jsonConsumer(responseParsed);
                    }
                  } catch(error) {
                    // text is not a valid json so we will consume as text
                  }
                  if (Api.debug) {
                    console.log("RESPONSE(Txt)", responseString);
                  }
                  return txtConsumer(responseString);
                })();
              }
            

            然后调整其余处理程序变得更加容易:

            class Api {
              static debug = true;
            
              static contribute(entryToAdd) {
                return new Promise((resolve, reject) => {
                  fetch('/api/contributions',
                    { method: 'POST',
                      headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
                      body: JSON.stringify(entryToAdd) })
                  .catch(reject);
                  .then(response => Api.consumeResponseBodyAs(response,
                      (json) => {
                        if (!response.ok) {
                          // valid json: reject will use error.details or error.message or http status
                          reject((json && json.details) || (json && json.message) || response.status);
                        } else {
                          resolve(json);
                        }
                      },
                      (txt) => reject(txt)// not json: reject with text payload
                    )
                  );
                });
              }
            

            【讨论】:

              【解决方案11】:

              我在 fetch 上遇到了同样的问题,并决定切换到 axios。马上修复问题,这里是代码sn-p。

              var axios = require('axios');
              
                var config = {
                  method: 'get',
                  url: 'http://localhost:4000/'
                };
                
                axios(config)
                .then(function (response) {
                  console.log(JSON.stringify(response.data));
                })
                .catch(function (error) {
                  console.log(error);
                });
              

              【讨论】:

                【解决方案12】:

                我在尝试从“/src”文件夹中获取数据时也遇到了同样的问题。将文件移动到“/public”为我解决了这个问题。

                【讨论】:

                  【解决方案13】:

                  虽然我从另一个 Web 服务器而不是本地请求数据,但我遇到了同样的问题。响应状态码是 200,但我仍然没有得到数据,即使它默认以 JSON 格式发送。 (简单的)问题是我忘记在 url 中包含“https://”,所以一开始它使用了本地主机。

                  【讨论】:

                    【解决方案14】:

                    我在 src 文件夹中有 .json 文件。只需将它移到 public 文件夹中,它就可以工作了

                    【讨论】:

                      【解决方案15】:

                      尝试将响应转换为字符串,然后将其解析为 JSON。这解决了我的错误。以下是相同的代码。

                      let resp = JSON.stringify(response);
                      res = JSON.parse(resp);
                      

                      【讨论】:

                        【解决方案16】:

                        我在同样的问题上苦苦挣扎,但在进行了一些研究后找到了解决方案。 这个问题有时是由打字错误引起的。您的控制台会告诉您错误的类型。

                        这是我发现的方法:在 settings.py 我写了一个双下划线:CORS__ORIGIN_ALLOW_ALL = True 而不是 CORS_ORIGIN_ALLOW_ALL = True.

                        问题仍然存在,我更改了这个“API Fetch 方法”,它工作得很好:

                        refreshList() {
                          fetch(process.env.REACT_APP_API+ "department")
                            .then((response) => response.json())
                            .then((data) => {
                              this.setState({ deps: data });
                            });
                        }
                        

                        到:

                        refreshList() {
                          fetch("http://127.0.0.1:8000/" + "department")
                            .then((response) => response.json())
                            .then((data) => {
                              this.setState({ deps: data });
                            });
                        }
                        

                        【讨论】:

                        • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
                        【解决方案17】:

                        对我来说,我正在从一台新计算机上使用 fetch 进行调用,但我忘记添加 env 文件来填充 process.env.REACT_APP_URLprocess.env.REACT_APP_API_KEY 字段。重新添加 .env 文件解决了这个问题。

                        【讨论】:

                          猜你喜欢
                          • 2017-12-15
                          • 2021-06-06
                          • 2021-03-02
                          • 2021-02-15
                          • 2020-04-18
                          • 1970-01-01
                          • 2020-03-26
                          • 2020-10-10
                          相关资源
                          最近更新 更多