简体   繁体   中英

How to access data from spring-boot backend to manipulate in reactjs frontend?

I'm developing a web application using spring-boot in backend and reactjs in frontend, I used webpack and babel to bundle react files. The environment setup is okay, and the frontend is working fine. But I'm stuck on communication between frontend and backend.

Clearly, my question is how can I get data from the spring boot to serve them in a react component?

Here is my @RestController class :

I tried to research all over, on the internet, went to this tuto https://spring.io/guides/tutorials/react-and-spring-data-rest/ where they explain cleary but there is something sopisticated, that I didn't capture very well in my mind, so that I may develop my own code, to access the backend data they use a line of code

`client({method: 'GET', path: '/api/employees'}).done(response => {
            this.setState({employees: response.entity._embedded.employees});` 

but this code is not clear. Also this question is not a duplicate of this How to integrate ReactJS with spring Boot because it doesn't answer it. Anyone can help me.

package scholar.reactspringwebpack.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import scholar.reactspringwebpack.entities.PrmEntity;
import scholar.reactspringwebpack.services.PrmServices;

import java.util.List;

@RestController
@CrossOrigin
public class DataController {

    @Autowired
    PrmServices prmServices;

    @GetMapping(value = "/all")
    public List<PrmEntity>readAll(){
        return prmServices.readAllUsers();
    }
}`

and here is my reactjs component : 

    import React, { Component } from 'react';
import axios from 'axios';

class SignupForm extends Component {
    state={
        fname: "",
        lname: "",
        depart: "",
        username: "",
        password: "",
        account_type: ""
    }
    componentDidMount(){
        axios.get("http://localhost:8080/all").then(res =>{
            const persons = res.data;
            this.setState({
                fname:persons.fname,
                lname:persons.lname,
                depart:persons.depart,
                username:persons.username,
                password:persons.password,
                account_type:persons.account_type
            });
        });
    }
  render() {
      const {users} = this.state;
      console.log(users);
    //   const userList = users.map(user=>{
    //       return(
    //           <table>
    //               <thead>
    //                   <tr>
    //                       <th>fname</th>
    //                       <th>lname</th>
    //                       <th>depart</th>
    //                       <th>username</th>
    //                       <th>password</th>
    //                       <th>account_type</th>
    //                   </tr>
    //               </thead>
    //               <tbody>
    //                   <tr>
    //                       <td>{user.fname}</td>
    //                       <td>{user.lname}</td>
    //                       <td>{user.depart}</td>
    //                       <td>{user.username}</td>
    //                       <td>{user.password}</td>
    //                       <td>{user.account_type}</td>
    //                   </tr>

    //               </tbody>
    //           </table>
    //       )
    //   })
    return (

        <div className="container">
            <div className="row">
                <div className="col-md-6 text-center signup-form ml-auto mr-5 card">
                    <div className="card-header">
                        <h3 className="text-info">Sign Up Form</h3>
                    </div>

                    <div className="card-body">
                        <form className="container">
                            <div className="form-group form-row">
                                <input
                                    type="text"
                                    name="fname"
                                    placeholder="Enter family name"
                                    className="input-text bg-transparent text-white form-control form-control-sm"
                                />
                            </div>

                            <div className="form-group form-row">
                                <input
                                    type="text"
                                    name="lname"
                                    placeholder="Enter last name"
                                    className="input-text bg-transparent text-white form-control form-control-sm" />

                            </div>




                            <div className="form-group form-row">
                                <select
                                    name="depart"
                                    className="input-text bg-transparent text-info custom-select custom-select-sm">
                                    <option value="">--Select your department--</option>
                                    <option value="administration">Administration</option>
                                    <option value="anaesthesia">Anaesthesia</option>
                                    <option value="palliative_care">Palliative care</option>
                                    <option value="petite_chgie">Petite chirirugie</option>
                                </select>
                            </div>
                            <div className="form-group form-row">
                                <input
                                    type="text"
                                    name="username"
                                    placeholder="Enter your username"
                                    className="input-text bg-transparent text-white form-control form-control-sm"
                                    />

                            </div>
                            <div className="form-group form-row">
                                <input
                                    type="password"
                                    name="password"
                                    placeholder="Enter password"
                                    className="input-text bg-transparent text-white form-control form-control-sm"
                                     />

                            </div>
                            <div className="form-group form-row">
                                <input
                                    type="password"
                                    name="confirm_password"
                                    placeholder="Confirm your password"
                                    className="input-text bg-transparent text-white form-control form-control-sm" />
                            </div>
                            <div className="">
                                <select
                                    name="account_type"
                                    className="input-text bg-transparent text-info custom-select custom-select-sm">
                                    <option value="">--Select your account type--</option>
                                    <option value="normal_user">Normal user</option>
                                    <option value="data_manager">Data Manager</option>
                                    <option value="head_of_dpt">Head of department</option>
                                    <option value="system_admin">System administrator</option>
                                </select>

                            </div>
                            <div className="form-group form-row">
                                <button name="signup_btn" className="mt-2 btn btn-block btn-outline-primary btn-sm">Sign up</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    )
  }
}

export default SignupForm;

React is in the front-end, Spring in the back-end. They communicate via HTTP - just like most of the internet traffic, so there's no particular guide for React + Spring.

Make sure React makes working HTTP requests, example (which is pure JS by the way, React is not needed in my example):

fetch('http://my.api.com/api/employees')
  .then(resp => resp.json())
  .then(data => this.setState({employees: data.employees}})

And also make sure that your back-end is serving what you want, you can use curl or postman to debug it.

Last but not least, make sure that your front-end and your back-end are allowed to communicate to each other by properly configuring your CORS headers in your back-end.

In order for your Frontend to be able to read your responses, you need to send a readable format like JSON. You can't just return Objects.

First you can use @ResponseBody to tell Spring to write something in there. Now you need to serialize your object to string, in order to be able to write it in your HTTP-ResponseBody.

To do this, you can use Jackson(recommended! -> https://www.baeldung.com/jackson-object-mapper-tutorial ) or just an ObjectMapper():

Example:

@GetMapping(value = "/all")
@ResponseBody
public String readAll(){
  ObjectMapper mapper = new ObjectMapper();
  user = prmServices.getUser(1);
  return mapper.writeValueAsString(user)
}

You can now request that endpoint, as stated above:

fetch('http://my.api.com/all')
  .then(resp => resp.json())
  .then(data => this.setState({user: data}})

In order to understand whats happening, look in the Network-Tab in your Chrome while making the request. The request should be there, and under "response" you can see what your Spring App is sending back. If it is not a clean JSON, i recommend you read the link i gave you above to serialize propperly. I am not familiar with react, but from that point on you should be fine, since any JS can handle JSON.

Sry for faulty Java-Syntax, last time i wrote Java 3 years ago ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM