React Js:Uncaught(在promise中)SyntaxError:意外的标记<在位置0的JSON中

时间:2016-05-17 07:31:13

标签: javascript json ajax reactjs

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

Uncaught (in promise) SyntaxError: Unexpected token < 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"
}

15 个答案:

答案 0 :(得分:28)

将两个标题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");});
}

答案 1 :(得分:4)

可以收到此错误,但请注意,这可能是对实际问题的警告。在我的情况下,JSON并没有出现错误状态,而是出现了404错误,它无法将JSON数据放在第一位进行处理,从而导致了此错误。

此问题的解决方法是,为了在本地项目中的fetch文件上使用.json,必须可以访问.json文件。可以通过将其放置在项目根目录中的文件夹中,例如public文件夹中来完成此操作。将json文件移到该文件夹​​后,404变成了200,Unexpected token < in JSON at position 0错误就解决了。

答案 2 :(得分:3)

对我有用的解决方案是: 我将data.json文件从src移到了公共目录。 然后使用提取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显式移动到公共目录。

答案 3 :(得分:2)

我在提取时遇到了同样的问题,并决定切换到axios。立即修复了此问题,这是代码段。

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

答案 4 :(得分:2)

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

答案 5 :(得分:1)

我确认此处提出的一些方法也对我有用:您必须将本地.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

然后一切都很好:)

答案 6 :(得分:0)

当您正在使用的API未发送相应的JSON时可能会出现。 您可能会以404页面或类似HTML / XML响应的形式遇到响应。

答案 7 :(得分:0)

关于您的承诺答复 您要求

response.json() 

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

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

res.json(YOUR-DATA-RESPONSE)

答案 8 :(得分:0)

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

在这种情况下,您将需要处理以下两种情况: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
        )
      );
    });
  }

答案 9 :(得分:0)

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

答案 10 :(得分:0)

我在 src 文件夹中有 .json 文件。只需将其移动到 public 文件夹中即可运行

答案 11 :(得分:0)

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

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

答案 12 :(得分:-1)

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

response => response.json()

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

答案 13 :(得分:-1)

我遇到了错误。 我只是在package.json中添加了“ proxy”,错误消失了。 错误仅存在于此,因为API请求是在与React应用程序运行相同的端口上发出的。您需要提供代理,以便可以对运行后端服务器的端口进行API调用。

答案 14 :(得分:-2)

这主要是因为您的React / Client应用中存在问题。将此行添加到您的客户package.json解决它

  

&#34;代理&#34;:&#34; http://localhost:5000/&#34;

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

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