简体   繁体   中英

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

I am following this tutorial:

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

When I start the React server and try to fetch the json object(s) from REST API and display them in the map, the player data is not displayed despite following the tutorial.

The only thing displayed is the word 'Players' but no player data is shown.

In the console I am getting:

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

The API works correctly and when I visit http://localhost:8080/players I am displayed a json object of all the players data.

[{"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;

In my package.json file I have:

"proxy": "http://localhost:8080"

And my SpringBoot REST application runs on 8080.

When I did 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();
    }
}

Thanks for help!

The response that you are getting is not JSON. It is string

Please follow this link it will help https://daveceddia.com/unexpected-token-in-json-at-position-0/

I am not sure but even if the file is in your local system you have to write http:// or https:// for fetch in javascript. Today I was using fetch with an api an the api started with www. I did not notice and used fetched and got the same error. But we I replaced www. with https:// the error got resolved

this error is because of cross-origin policy and there is many ways to fix that. One is to use cor packag with your node server. but I fixed this in development mode by adding a middlware. and also you don't need to add proxy in your package.josn

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM