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

Posted

技术标签:

【中文标题】Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 from SpringBoot API【英文标题】: 【发布时间】: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":"F***o","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 是什么? 【参考方案1】:

您得到的响应不是 JSON。是字符串

请点击此链接,这将有助于https://daveceddia.com/unexpected-token-in-json-at-position-0/

【讨论】:

嘿,我将响应记录为文本并获得了一个已添加到问题中的 HTML 模板,但我该如何解决这个问题?谢谢。【参考方案2】:

我不确定,但即使文件在您的本地系统中,您也必须编写 http:// 或 https:// 以在 javascript 中获取。今天我使用 fetch 和一个 api,这个 api 以 www 开头。我没有注意到并使用了 fetched 并得到了同样的错误。但我们我换成了 www。使用 https:// 错误得到解决

【讨论】:

谢谢,但是当我尝试使用 http/https 获取“localhost:8080/players”时,它显示“类型错误:无法获取”,我的意思是教程只显示了“/clients”以及代理在localhost:8080 上,所以我认为它会自动执行此操作。 你能不能再试试这样的“localhost:8080/players”?我认为它应该像这样与这个 http:// 一起工作 我尝试添加 'http://' 'localhost:8080' 然后在 app.js 中添加了 '/players' 但 fetch 给出了 Type Error const response = await fetch('@987654324 @); const body = 等待 response.json(); this.setState(players: body); 实际上,我只是这样做并在控制台中查看它说: localhost/:1 Access to fetch at 'localhost:8080/players' from origin 'localhost:3000' has been blocked by CORS policy: No请求的资源上存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。如何在 fetch 中添加“no-cors”? 我在控制器中添加了@CrossOrigin(origins = "localhost:3000"),现在它可以工作了,感谢您的帮助。

以上是关于Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 from SpringBoot API的主要内容,如果未能解决你的问题,请参考以下文章

解决Uncaught (in promise) reason的问题

Uncaught (in Promise) DOMException: play() 只能由用户手势启动

解决Uncaught (in promise) reason的问题

Uncaught (in promise):消息端口在收到响应之前关闭

vue控制台报 Uncaught (in promise) TypeError:

Uncaught (in promise) TypeError: Cannot set properties of null (setting 'innerText') in OpenWetherMa