java - 如何从 spring-boot 后端访问数据以在 reactjs 前端进行操作?
问题描述
我正在使用后端的 spring-boot 和前端的 reactjs 开发一个 Web 应用程序,我使用 webpack 和 babel 来捆绑反应文件。环境设置没问题,前端工作正常。但我被困在前端和后端之间的通信上。
显然,我的问题是如何从 Spring Boot 中获取数据以在 React 组件中为它们提供服务?
这是我的@RestController class
:
我试图在互联网上进行全面研究,去了这个教程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;
解决方案
为了让您的前端能够读取您的响应,您需要发送像 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 中的网络选项卡。请求应该在那里,在“响应”下,您可以看到您的 Spring 应用程序发回的内容。如果它不是一个干净的 JSON,我建议您阅读我在上面给您的链接以正确序列化。我不熟悉反应,但从那时起你应该没问题,因为任何 JS 都可以处理 JSON。
抱歉,Java 语法有问题,上次我在 3 年前编写 Java 时;)
推荐阅读
- swift - 更改字典中键的类型
- python - Pandas 索引 if 语句
- javascript - 减少对特定 HTML 表单元素执行的验证次数。
- javascript - 我想给 jQuery Slider 很多价值
- ios - 字符串不是空时被验证为空
- identityserver4 - 使用 IdentityServer4 从数据库显式登录/注销自定义用户
- arrays - 不能在属性初始化程序中使用实例成员“国家”;属性初始化程序在“自我”可用之前运行
- javascript - 粘性菜单/导航,固定菜单时框阴影不起作用
- types - 榆树中的“数字”是什么
- javascript - 使用 onclick() 从数据库中获取详细信息