[英]How to access data from spring-boot backend to manipulate in reactjs frontend?
我正在后端使用spring-boot和前端使用reactjs开发一个Web应用程序,我使用webpack和babel捆绑了react文件。 环境设置可以,并且前端工作正常。 但是我被困在前端和后端之间的通信上。
显然,我的问题是如何从Spring Boot中获取数据以将它们提供给react组件?
这是我的@RestController class
:
我尝试在互联网上进行全面研究,访问了此Tuto https://spring.io/guides/tutorials/react-and-spring-data-rest/ ,在其中他们清楚地解释了问题,但有些复杂,我没有在我的脑海中无法很好地捕捉,因此我可以开发自己的代码,以访问他们使用一行代码的后端数据
`client({method: 'GET', path: '/api/employees'}).done(response => {
this.setState({employees: response.entity._embedded.employees});`
但是这段代码不清楚。 这个问题也不是如何将ReactJS与spring boot集成的重复,因为它没有回答。 任何人都可以帮助我。
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在前端,Spring在后端。 它们通过HTTP进行通信-就像大多数互联网流量一样,因此没有关于React + Spring的特殊指南。
确保React发出有效的HTTP请求,例如(顺便说一下,它是纯JS,在我的示例中不需要React):
fetch('http://my.api.com/api/employees')
.then(resp => resp.json())
.then(data => this.setState({employees: data.employees}})
还要确保您的后端能够满足您的需求,您可以使用curl或邮递员对其进行调试。
最后但并非最不重要的一点是,通过在后端中正确配置CORS标头 ,确保允许您的前端和后端相互通信。
为了使您的前端能够读取您的响应,您需要发送一种可读格式,例如JSON。 您不能只返回对象。
首先,您可以使用@ResponseBody告诉Spring在其中编写一些内容。 现在,您需要将对象序列化为字符串,以便能够在HTTP-ResponseBody中编写它。
为此,您可以使用Jackson(推荐!-> https://www.baeldung.com/jackson-object-mapper-tutorial )或仅使用ObjectMapper():
例:
@GetMapping(value = "/all")
@ResponseBody
public String readAll(){
ObjectMapper mapper = new ObjectMapper();
user = prmServices.getUser(1);
return mapper.writeValueAsString(user)
}
如上所述,您现在可以请求该端点:
fetch('http://my.api.com/all')
.then(resp => resp.json())
.then(data => this.setState({user: data}})
为了了解发生了什么,请在发出请求的同时查看Chrome中的Network-Tab。 该请求应该在那里,在“响应”下,您可以看到您的Spring App正在发回什么。 如果不是干净的JSON,建议您阅读上面给我的链接以正确进行序列化。 我不熟悉react,但是从那时起您应该可以了,因为任何JS都可以处理JSON。
对错误的Java语法表示抱歉,我3年前的上次编写Java;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.