1 ReactJs and SpringBoot
djmil edited this page 2024-11-24 18:25:23 +01:00
This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Backend

In SpringInitializer, create a simple SpringBoot RESTfull app to server bad jokes.n Be sure to select SpringWeb component.

src/main/java/djmil/cordacheckers/Joke.java

package djmil.cordacheckers;

public record Joke(String joke) { }

src/main/java/djmil/cordacheckers/ApiController.java

package djmil.cordacheckers;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {
    
    @GetMapping("/api/badjokes")
    public ResponseEntity<Joke> badJokes() {
        Joke joke = new Joke("What do you call a fly without wings? A walk!");
        return ResponseEntity.ok(joke);
    }
   
}

Run backend and check http://localhost:8080/api/badjokes. You should see JSON file with a joke inside.

Frontend

Now, let's create a React WebApp. Its super easy to get started with React by using create-react-app. If you have the necessary tools installed (e.g. node, npm), you can just execute this command

npx create-react-app enter-app-name-here

Since we are going host front end app by itself (via node) it does not meter where exactly to place the generated web app.

webapp/src/App.js

import './App.css';
import React, { useState, useEffect } from 'react';

function App() {

  const [joke, setJoke] = useState([]);
  useEffect(() => {
     fetch('/api/badjokes')
        .then((response) => response.json())
        .then((data) => {
           console.log(data.joke);
           setJoke(data.joke);
        })
        .catch((err) => {
           console.log(err.message);
        });
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <p>         
          Here is your joke: {joke}
        </p>
      </header>
    </div>
  );
}

export default App;

Run the app with npm start command

Proxy

By default React uses 3000 port. And all REST requests would fail, because SpringBoot serves on 8080. To fix this issue in your dev environment, add this line to the package.json

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

This will configure underline server to redirect (proxy) all requests to specified domain. More granular configuration is also possible.