Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fetching String Value in React from a Spring Boot backend

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading