[英]Unable to fetch data using React/Spring
在Spring / React應用上工作。 Fetch並沒有獲取任何數據(至少沒有呈現任何數據),但是如果我轉到Spring服務器(本地主機),數據肯定在那里。 要返回的數據是一個2d數組-這可能是JSON問題嗎?
這是我的App.js
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
isLoading: true,
groups: [] };
}
componentDidMount() {
fetch('/api/test')
.then(res => res.json())
.then(data => this.setState({ groups: data });
}
render() {
return (
<div>
<p> {this.state.groups} </p>
</div>
);
}
}
export default App;
這是我的控制器
package hello;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.CrossOrigin;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Optional;
@RestController
@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping("/api")
public class HelloController {
public Map a = new Map();
@GetMapping("/test")
Tile[][] b() {
return a.getMap();
}
}
您的spring應用程序與React應用程序不在同一端口上運行,盡管您的獲取操作與React在同一服務器上請求資源,而無需代理或更改請求基本URL,您將無法從spring應用程序中得到任何東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.