我正在關注本教程:
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":"[email protected]","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}]
應用程式.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();
}
}
感謝幫助!
uj5u.com熱心網友回復:
您得到的回應不是 JSON。它是字串
請點擊此鏈接,它會有所幫助https://daveceddia.com/unexpected-token-in-json-at-position-0/
uj5u.com熱心網友回復:
我不確定,但即使檔案在您的本地系統中,您也必須在 javascript 中撰寫 http:// 或 https:// 來獲取。今天我在一個 api 中使用 fetch 一個以 www 開頭的 api。我沒有注意到并使用了 fetched 并得到了同樣的錯誤。但我們我替換了 www。使用 https:// 錯誤得到解決
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352814.html
標籤:javascript 反应 json 春天 弹簧靴
