【问题标题】:Spring Boots Json data failed to retrieve with React Js AppSpring Boots Json 数据无法使用 React Js App 检索
【发布时间】:2022-01-25 23:28:55
【问题描述】:

我使用 reactjs 开发前端,后端我使用 spring rest API 来检索数据。我的数据保存到 Jason 文件到 spring boot 项目目录中。这是json文件数据示例。

{
    "id": 2,
    "name": "Aberconwy",
    "seqNo": 1,
    "partyResults": [
        {
            "party": "LAB",
            "votes": 8994,
            "share": 33.00
        },
        {
            "party": "CON",
            "votes": 7924,
            "share": 29.10
        },
        {
            "party": "LD",
            "votes": 5197,
            "share": 19.10
        },
        {
            "party": "PC",
            "votes": 3818,
            "share": 14.00
        },
        {
            "party": "OTH",
            "votes": 517,
            "share": 1.90
        },
        {
            "party": "GRN",
            "votes": 512,
            "share": 1.90
        },
        {
            "party": "UKIP",
            "votes": 296,
            "share": 1.10
        }
    ]
}

项目结构。

我想从这个 json 文件中显示派对名称、投票并分享到 react js 应用程序中。

这是课程。

 public class PartyResult {
       String party;
       Integer votes;
       BigDecimal share;
    }

这里是spring boots中的接口代码。

List<PartyResult> GetAllPartyResult();

这里是存储库。

@Override
    public List<PartyResult> GetAllPartyResult() {
        return (List<PartyResult>) results;
    }

这是休息控制器。

 @RestController
public class ResultsController {

    private final ResultService results;

    public ResultsController(ResultService resultService) {
        this.results = resultService;
    }

    @GetMapping("/result/{id}")
    ConstituencyResult getResult(@PathVariable Integer id) {
        ConstituencyResult result = results.GetResult(id);
        if (result == null) {
            throw new ResultNotFoundException(id);
        }
        return results.GetResult(id);
    }

    @PostMapping("/result")
    ResponseEntity<String> newResult(@RequestBody ConstituencyResult result) {
        if (result.getId() != null) {
            results.NewResult(result);
            return ResponseEntity.created(URI.create("/result/"+result.getId())).build();
        }
        return ResponseEntity.badRequest().body("Id was null");
    }

    @GetMapping("/scoreboard")
    Scoreboard getScoreboard() {
        return new Scoreboard();
    }
    
    @GetMapping("/partyresult")
    public List<PartyResult> GetAllPartyResult()  {
        
        return (List<PartyResult>) PartyResult.builder();
        
    }
    
}

这里是 react js app.js 代码。

function App() {
  return (
    <div>
    <Router>
          <HeaderComponent />
            <div className="container">
                <Routes> 
                      <Route path = "/List" exact component = {ListResultComponent}></Route>
                      
                </Routes>
            </div>
          <FooterComponent />
    </Router>
</div>
  );
}

export default App;

这是组件中的代码。

import React, { Component } from 'react'
import ElectionService from '../services/ElectionService'

class ListResultComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
            constituencyresult: []
        }
    }

        componentDidMount(){
            ElectionService.getResult().then((res) => {
                this.setState({ constituencyresult: res.data});
            });
        }
        
    

    

    render() {
        return (
            <div>
                 <h2 className="text-center">Election Result List</h2>
                
                 <br></br>
                 <div className = "row">
                        <table className = "table table-striped table-bordered">

                            <thead>
                                <tr>
                                    <th> Party Name</th>
                                    <th> Votes</th>
                                    <th> Share</th>
                                    
                                </tr>
                            </thead>
                            <tbody>
                                {
                                    this.state.constituencyresult.map(
                                        constituencyresult => 
                                        <tr>
                                             <td> { constituencyresult.name} </td>   
                                             <td> {constituencyresult.votes}</td>
                                             <td> {constituencyresult.share}</td>
                                             
                                        </tr>
                                    )
                                }
                            </tbody>
                        </table>

                 </div>

            </div>
        )
    }
}

export default ListResultComponent

这里是服务类。

import axios from 'axios';

const ELECTION_API_BASE_URL = "http://localhost:8080/partyresult";

class ElectionService {

    getResult(){
        return axios.get(ELECTION_API_BASE_URL);
    }

    
}

export default new ElectionService()

这是应用程序在运行时的屏幕截图,它是空的,我希望数据应该显示到反应应用程序中。

【问题讨论】:

  • 您是否在控制台中遇到任何错误?应用程序日志文件中的任何错误怎么办?
  • Whitelabel 错误页面 此应用程序没有明确的 /error 映射,因此您将其视为后备。 2021 年 12 月 26 日星期日 16:33:46 GMT 出现意外错误(类型=未找到,状态=404)。
  • 用这个网址http://localhost:8080/partyresult @blurfus

标签: reactjs json spring spring-boot spring-rest


【解决方案1】:

您可以在ListResultComponent 中使用以下代码获得派对:

ElectionService.getResult().then((res) => {
    this.setState({ constituencyresult: res.partyResults});
});

根据你发送的json数据替换res.partyResults而不是res.data

【讨论】:

  • 我必须在 API 中进行任何更改吗?
  • 同样的结果。不显示数据
  • 您的 API 听起来不错。您是否在 RestController 类之上设置了任何 @RequestMapping 而不是默认值?
  • 我为控制器添加了整个代码。我不是简单地请求 / 而是在 /partyresult 中提到了我
  • 您在调用localhost:8080/partyresult 时提到了get (type=Not Found, status=404)。您是否在 application.properties 或 yml 中设置了 server.servlet.context-path
猜你喜欢
  • 2018-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-07
  • 2021-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多