如果我使用curl命令,服务器将返回一个帖子对象数组,格式如下:
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"
}
}
}
]
我尝试使用fetch 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);
});
}
但是我遇到了这个错误:
JSON 中位置 0 处出现意外的 < 符号
SyntaxError: JSON 中位置 0 处出现意外的 < 符号
我该如何解决这个问题?请你帮帮我。谢谢。
response.text()
而不是response.json()
来查看你实际上接收到了什么。 - Jaromanda X