javascript 未捕获(在承诺中)语法错误:SpringBoot API中JSON位置0处的意外标记〈

mnemlml8  于 2023-01-24  发布在  Java
关注(0)|答案(3)|浏览(162)

我正在遵循此教程:
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/player时,显示了所有球员数据的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();
    }
}

多谢帮忙!

h22fl7wq

h22fl7wq1#

您得到的响应不是JSON,而是字符串
请点击此链接,它将帮助https://daveceddia.com/unexpected-token-in-json-at-position-0/

ergxz8rk

ergxz8rk2#

我不确定,但即使文件在您的本地系统中,您也必须编写http://或https://以便在JavaScript中获取。今天我使用fetch和API,但api以www开头。我没有注意到,使用fetch时出现了相同的错误。但我们将www替换为https://,错误得到了解决

snz8szmq

snz8szmq3#

这个错误是因为交叉来源策略,并且有很多方法来修正它.一个是使用cor packag与你的节点服务器.但是我修正了这个在开发模式通过添加一个中间件.并且你也不需要添加代理在你的包.josn

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

相关问题