【发布时间】:2021-12-21 08:15:16
【问题描述】:
我正在学习本教程:
https://www.baeldung.com/spring-boot-react-crud
当我启动 React 服务器并尝试从 REST API 获取 json 对象并将它们显示在地图中时,尽管按照教程进行操作,但仍不显示玩家数据。
唯一显示的是“玩家”一词,但没有显示玩家数据。
在我得到的控制台中:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
API 工作正常,当我访问 http://localhost:8080/players 时,会显示所有玩家数据的 json 对象。
[{"id":1,"firstName":"Fabiano","lastName":"Caruana","email":"fabcar@gmail.com","bio":"Not quite WC.","password":"BigFab72","rating":2750"},
{"id":2,"firstName":"Biggie","lastName":"Ta","email":"bigt@gmail.com", "bio":"Not quite a WC.","password":"BigT72","rating":2750}]
app.js:
import React, {Component} from 'react';
class App extends Component {
state = {
players: []
};
async componentDidMount() {
const response = await fetch('/players');
const body = await response.json();
this.setState({players: body});
}
render() {
const {players} = this.state;
return (
<div className="App">
<header className="App-header">
<div className="App-intro">
<h2>Players</h2>
{players.map(player =>
<div key={player.id}>
{player.firstName} ({player.email})
</div>
)}
</div>
</header>
</div>
);
}
}
export default App;
在我的 package.json 文件中,我有:
"proxy": "http://localhost:8080"
我的 SpringBoot REST 应用程序在 8080 上运行。
当我做 console.log(response.text()):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="/manifest.json" />
<!--
Notice the use of in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script src="/static/js/bundle.js"></script><script src="/static/js/vendors~main.chunk.js"></script><script src="/static/js/main.chunk.js"></script></body>
</html>
控制器:
@RestController
@RequestMapping("/players")
public class PlayersController {
private final PlayerRepository playerRepository;
public PlayersController(PlayerRepository playerRepository) {
this.playerRepository = playerRepository;
}
@GetMapping
public List<Player> getPlayers() {
return playerRepository.findAll();
}
@GetMapping("/{id}")
public Player getPlayer(@PathVariable Long id) {
return playerRepository.findById(id).orElseThrow(RuntimeException::new);
}
@PostMapping()
public ResponseEntity createPlayer(@RequestBody Player player) throws URISyntaxException {
Player savedPlayer = playerRepository.save(player);
return ResponseEntity.created(new URI("/players/" + savedPlayer.getId())).body(savedPlayer);
}
@PutMapping("/{id}")
public ResponseEntity updatePlayer(@PathVariable Long id, @RequestBody Player player) {
Player currentPlayer = playerRepository.findById(id).orElseThrow(RuntimeException::new);
currentPlayer.setFirstName(player.getFirstName());
currentPlayer.setEmail(player.getEmail());
currentPlayer = playerRepository.save(player);
return ResponseEntity.ok(currentPlayer);
}
@DeleteMapping("/{id}")
public ResponseEntity deletePlayer(@PathVariable Long id) {
playerRepository.deleteById(id);
return ResponseEntity.ok().build();
}
}
感谢您的帮助!
【问题讨论】:
-
那么看看实际返回的是什么。这基本上是说您返回的是 HTML 页面,而不是 JSON。可能是错误页面。查看网络面板,查看请求
-
此错误通常意味着您的服务器返回的是 HTML 而不是 JSON。
-
@epascarello 我有一个 HTML 模板,已将其添加到问题中,感谢您的帮助。你知道我该如何解决这个问题吗?
-
看来您的路由不正确
-
它正在获取的网络面板中的 URL 是什么?
标签: javascript reactjs json spring spring-boot