Spring + React获取数据

时间:2018-11-14 18:18:21

标签: json spring reactjs api

我遇到了从spring暴露的api获取数据的问题。 我想通过以下方式获取数据:

componentDidMount() {
this.setState({isLoading: true});

fetch('http://localhost:8080/api/tasks/')
.then(response => { return response.json() })
.then(results => this.setState({
  tasks: results,
  isLoading: false
}));

返回数据的spring api:

    @CrossOrigin(origins = "http://localhost:3000")
  @GetMapping
  public List<Task> findTasksByUserId() {
    return taskService.findTasksBelongToUser(idProvider.getCurrentUserId());
  }

返回的JSON:

[
{
id: 1,
version: 0,
name: "Task1",
description: "description1",
priority: 1,
finished: true,
category: {
id: 1,
version: 0,
name: "Uncategorized",
user: {
id: 1,
version: 0,
login: "admin",
email: "admin@todo.pl",
enabled: true
}
},
user: {
id: 1,
version: 0,
login: "admin",
email: "admin@todo.pl",
enabled: true
},
position: 0
},
{
id: 2,
version: 0,
name: "Task2",
description: "description2",
priority: 4,
finished: true,
category: {
id: 1,
version: 0,
name: "Uncategorized",
user: {
id: 1,
version: 0,
login: "admin",
email: "admin@todo.pl",
enabled: true
}
},
user: {
id: 1,
version: 0,
login: "admin",
email: "admin@todo.pl",
enabled: true
},
position: 1
}]

我得到了这样的错误:

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

我不知道出了什么问题,但是json的格式可能不正确,因为它以符号[[]开头。 我是React的初学者,因此请提供一些提示和帮助。 问候

1 个答案:

答案 0 :(得分:1)

fetch()返回一个Promise,它当然会解析为HTTP响应,而不是实际的JSON。要从响应中提取JSON正文内容,我们使用json()方法。

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

fetch('http://localhost:8080/api/tasks/', {
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }

    })
.then(response => { return response.json() })
.then(results => this.setState({
  tasks: results,
  isLoading: false
}));