简体   繁体   English

无法使用React / Spring获取数据

[英]Unable to fetch data using React/Spring

Working on a Spring/React app. 在Spring / React应用上工作。 Fetch isn't getting any data (at least, nothing is being rendered) yet if I go to the Spring server (localhost) the data is definitely there. Fetch并没有获取任何数据(至少没有呈现任何数据),但是如果我转到Spring服务器(本地主机),数据肯定在那里。 The data to be returned is a 2d array - could this be a problem with JSON? 要返回的数据是一个2d数组-这可能是JSON问题吗?

Here he is my App.js 这是我的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;

Here's my controller 这是我的控制器

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.

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