react app and spring boot

djmil 2023-08-13 15:47:58 +02:00
parent b0f36ba13a
commit fb49e5019e

89
ReactJs and SpringBoot.md Normal file

@ -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<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`](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 (
<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`
```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.