如果我捲曲,服務器返回的帖子對象的數組,像這樣:意外標記<在JSON在位置0
curl http://localhost/api/posts/
[
{
"id": 7,
"target": {
"body": "This is the body",
"title": "Airbnb raising a reported $850M at a $30B valuation",
"user": {
"first_name": "ben",
"last_name": "jamin"
}
}
},
{
"id": 11,
"target": {
"body": "This is the body",
"title": "Browsing the APISSS",
"user": {
"first_name": "user",
"last_name": "two"
}
}
}
]
我嘗試這樣使用提取API獲得:
fromServer() {
console.log('fromServer')
var headers = new Headers();
headers.append('Accept', 'application/json');
let a = fetch('http://test.com/api/posts/', headers)
.then(function(response) {
if (response.status !== 200) {
console.log('There was a problem. Status Code: ' + response.status);
return;
}
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
}
但我得到這個錯誤:
Unexpected token < in JSON at position 0
SyntaxError: Unexpected token < in JSON at position 0
我該如何解決這個問題?你可以幫我嗎。謝謝。
有機會,您收到一個HTML文檔 - 嘗試'response.text()',而不是'response.json()'看你真的在收到 –
,完全取決於你 –
我認爲它應該是 - > 「.then(function(response)=> {...});」,you missing「=> 」。只是一個猜測。 – Rajesh