Home > front end >  Fetching String Value in React from a Spring Boot backend
Fetching String Value in React from a Spring Boot backend

Time:07-05

I am trying to fetch a string value from a spring boot api which is hosted on localhost:8080 using an api call from within my react app which runs on localhost:3000. The resulting json does not contain the desired string value.

Here's the spring boot controller.

HelloController.java

package com.pilot.helloworld.hello;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @CrossOrigin(origins = "http://localhost:3000/")
    @RequestMapping("/hello")
    public String sayHello(){
        return "Hello World!";
    }

}

And here are the React components I am using.

App.js

import Message from './components/Message';
import './App.css';

function App() {
  return (
    <div>
      <Message/>
    </div>
  );
}

export default App;

Message.js

import React, {useState} from "react";

function Message(){
    const [message, setMessage] = useState("");

    function getMessage(){
        
        fetch(`http://localhost:8080/hello`).then(res => {
            console.log(res.json());
            setMessage(res);
        })
    }    
    
    return(
        <div>
            <button onClick={getMessage}>Get Hello Message</button>
            <br/>
            <h1>{message}</h1>
        </div>
    );
};

export default Message;

Here is what the console shows.

Here is what the console shows

I am really at a loss here. Can't make sense out of these errors. Help greatly appreciated. Thanks!

CodePudding user response:

Your JavaScript client is expecting JSON format, but your Spring Boot backend is just returning a String "Hello World!". That is the reason JSON parse Syntax error.

Try returning a String, which contains JSON format.

  • Related