无法使用React / Spring获取数据

时间:2018-11-06 23:42:30

标签: javascript java spring reactjs

使用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();
    }
}

1 个答案:

答案 0 :(得分:0)

您的spring应用程序不在与React应用程序相同的端口上运行,尽管您的获取操作与React在同一个服务器上请求资源,而无需代理或更改请求基本url,您将无法从Spring获得任何东西应用程序。