2016-05-17 71 views
3

我想在反應js中獲取我的Json文件,對此我使用的是fetch。但它顯示了一個錯誤React Js:Uncaught(在promise中)SyntaxError:在位置0的JSON中意外的標記<

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" 
} 
+0

也許你會收到錯誤頁面的迴應,請查看開發人員工具中的網絡選項卡。 – jcubic

+0

是的。我在fr.json中得到了一些垃圾html。 – iamsaksham

+0

好的,我解決了這個問題。首先.json需要通過'localhost'加載。所以我改變了'fetch('http://localhost/img/fr.json')'。此外,我在localhost:8080上運行我的應用程序,因此發生了CORS問題,並通過chrome插件禁用了該問題。無論如何,非常感謝@jcubic提供的支持,因爲有時代碼中沒有任何錯誤。 – iamsaksham

回答

8

添加兩個頭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");}); 
} 
相關問題