簡體   English   中英

未捕獲(承諾)SyntaxError:意外令牌 < in JSON at position 0 來自 SpringBoot API

[英]Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 from SpringBoot API

我正在關注本教程:

https://www.baeldung.com/spring-boot-react-crud

當我啟動 React 服務器並嘗試從 REST API 獲取 json 對象並將它們顯示在 map 中時,盡管按照教程進行操作,但播放器數據並未顯示。

唯一顯示的是“玩家”一詞,但沒有顯示玩家數據。

在控制台中我得到:

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

API 正常工作,當我訪問 http://localhost:8080/players 時,我會看到所有玩家數據的 json object。

[{"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}]

應用程序.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>

Controller:

@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();
    }
}

感謝幫助!

您得到的響應不是 JSON。 它是字符串

請點擊此鏈接,它會有所幫助https://daveceddia.com/unexpected-token-in-json-at-position-0/

我不確定,但即使文件在您的本地系統中,您也必須在 javascript 中編寫 http:// 或 https:// 來獲取。 今天我在一個 api 中使用 fetch 一個以 www 開頭的 api。 我沒有注意到並使用了 fetched 並得到了同樣的錯誤。 但我們我替換了 www。 使用 https:// 錯誤得到解決

此錯誤是由於跨源策略引起的,有很多方法可以解決該問題。 一種是將 cor packag 與您的節點服務器一起使用。 但我通過添加中間件在開發模式下解決了這個問題。 而且您也不需要在 package.josn 中添加代理

app.use('/api/user', (req, res, next)=>{
  res.header("Access-Control-Allow-Origin", "http://localhost:3000");
  next();
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM