From fb49e5019ebc2a0b6106c8ccc2336ed8c34fc903 Mon Sep 17 00:00:00 2001 From: djmil Date: Sun, 13 Aug 2023 15:47:58 +0200 Subject: [PATCH] react app and spring boot --- ReactJs and SpringBoot.md | 89 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 ReactJs and SpringBoot.md diff --git a/ReactJs and SpringBoot.md b/ReactJs and SpringBoot.md new file mode 100644 index 0000000..28c488d --- /dev/null +++ b/ReactJs and SpringBoot.md @@ -0,0 +1,89 @@ +# 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`* +```java +package djmil.cordacheckers; + +public record Joke(String joke) { +} +``` + +*`src/main/java/djmil/cordacheckers/ApiController.java`* +```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 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. It’s super easy to get started with React by using [`create-react-app`](https://facebook.github.io/create-react-app/ "Create React App"). If you have the necessary tools installed (e.g. `node`, `npm`), you can just execute this command + +```bash +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`* +```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 ( +
+
+

+ Here is your joke: {joke} +

+
+
+ ); +} + +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` + +```json +"proxy": "http://localhost:8080", +``` + +This will configure underline server to redirect (proxy) all requests to specified domain. More [granular configuration](https://create-react-app.dev/docs/proxying-api-requests-in-development/) is also possible. \ No newline at end of file