简体   繁体   English

Spring + React 获取数据

[英]Spring + React fetch data

i have a problem with fetch data from api exposed by spring.我在从 spring 公开的 api 获取数据时遇到问题。 I want to fetch data by:我想通过以下方式获取数据:

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

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

The spring api which return data:返回数据的spring api:

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

Returned JSON:返回的 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
}]

And i got a error like this:我得到了这样的错误:

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

I dont know what is wrong but maybe format of json is not correct, because it's start with the sign '['.我不知道出了什么问题,但 json 的格式可能不正确,因为它以符号“[”开头。 I am a beginner in React so please about some hint and help.我是 React 的初学者,所以请提供一些提示和帮助。 regards问候

fetch() returns a promise which gets resolved into an HTTP response of course, not the actual JSON. fetch()返回一个承诺,当然,它被解析为 HTTP 响应,而不是实际的 JSON。 To extract the JSON body content from the response, we use the json() method.为了从响应中提取 JSON 正文内容,我们使用json()方法。

Try adding two headers Content-Type and Accept to be equal to application/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
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM