首页 > 解决方案 > 尝试从我的 Java 服务器获取数据时,为什么我的 React 应用程序中的 fetch() 不起作用?

问题描述

我知道 fetch() 负责从我的 java 服务器中获取解析的数据。但是,当我运行 React 应用程序时,该应用程序不会获取任何内容。

这是我的前端代码:

import React, {Component} from 'react'

export class PostList extends Component {
   
    constructor(props){
        super(props)
        this.state = {
            posts: Object
        }
    }

//A test API endpoint -> https://hacker-news.firebaseio.com/v0/item/29042728.json?print=pretty
    componentDidMount(){
       fetch('localhost:8080/hn/articles', {
      method: 'GET',

   })
   .then((response) => response.json())
   .then((responseJson) => {
      console.log(responseJson);
      this.setState({
         data: responseJson
      })
   })
   .catch((error) => {
      console.error(error);
   });
        }
    
    render(){
       const {posts} = this.state
        return(
            <div>
               <h1>Hacker News: Article Data</h1>
               <p>{posts.by}</p>
               <p>{posts.descendants}</p>
               <p>{posts.id}</p>
               <p>{posts.kids}</p>
               <p>{posts.score}</p>
               <p>{posts.time}</p>
               <p>{posts.title}</p>
               <p>{posts.type}</p>
               <p>{posts.url}</p>
            </div>
        )
    }
}

导航到本地浏览器时,会显示标题,但没有显示应该放置数据的类别。

我尝试在文件中指定数据类型:

fetch('localhost:8080/hn/articles', {
      method: 'GET',
      dataType: 'json',
   })

但还是一无所获。

任何帮助将不胜感激。如果有人需要我详细说明,请告诉我!

标签: javareactjsapiget

解决方案


推荐阅读