以下是Controller和Test.js代码
在Test.js里试了console.log()和setState()都获取不到数据。
写了text.json测试是可以用fetch()获取到里面的数据的,不知道为什么Controller的数据获取不到。
Controller用main方法测试过,api/staffs指向的staffs()方法可以获取到数据库的数据。
刷新页面,过半分钟console才报错:
Test.js:14 GET http://localhost:8080/api/staffs net::ERR_EMPTY_RESPONSE
错误出在fetch()命令。
新手求解,谢谢了!!
@RestController
@RequestMapping("/api")
public class StaffManagementController {
@Autowired
private StaffManagementFunctionImpl function = new StaffManagementFunctionImpl();
public StaffManagementController(StaffManagementFunctionImpl function) {
this.function = function;
}
@GetMapping("/staffs")
List<StaffManagement> staffs() {
return function.findAllStaff();
}
}
class Test extends Component {
constructor(props) {
super(props);
this.state = {staffs: []};
}
componentDidMount() {
fetch('api/staffs')
.then(response => response.json())
.then((result) => {console.log(result)})
//.then(item => this.setState({staffs: item.staffManagement}))
.catch(e=>{console.log("error")})
}
render() {
const staffs = this.state.staffs;
return (
<div>
<ul>
{staffs.map((item) => {
return <li key={item.id}>{item.name}</li>
})}
</ul>
</div>
)
}
}
export default Test;