【问题标题】:How to fetch data from Spring boot in react native?如何在本机反应中从 Spring Boot 中获取数据?
【发布时间】:2020-04-29 06:31:18
【问题描述】:

我有一个使用 react native expo 创建的前端,我的后端是使用 spring boot 完成的,当我在本地运行 spring boot 并在浏览器中键入 URL 时,模型位于谷歌云中(不部署“localhost URL”)它在浏览器上显示数据。如何在不部署谷歌云的情况下将这些数据获取到我的 react 本机应用程序。

 componentDidMount() {
     fetch('http://192.168.56.1:8080/users/toFrontend?email=meNewTwo@gmail.com')
       .then((response) => response.json())
       .then((json) => {
         this.setState({ data: json});
     })
      .catch((error) => console.error(error))
     .finally(() => {
       this.setState({ isLoading: false });
     });

这是我使用的代码

【问题讨论】:

    标签: spring-boot react-native fetch react-native-android expo


    【解决方案1】:
    fetch('http://{your IP}:8081/')
          .then((response) => response.json())
          .then((responseJson) => {
            this.setState({ message : responseJson.message.data })
            })
          .catch((error) => {
            console.error(error);
          }); 
    

    现在我们有了命令提示符,让我们输入ipconfig 按回车键并获取 IPv4 地址下的数字。这个数字是你的本地 IP。

    REST API

    fetch('http://{your IP}:8081/',{
              method: 'GET',// denpends upon your call POST or GET
              headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
              }
            })
        .then((response) => response.json())
        .then((responseJson) => {
    
           console.log(responseJson);
    
        })
        .catch((error) =>{
            console.error(error);
        });
    }
    

    这里是官方link

    【讨论】:

    • 它不起作用它给出一个网络错误为“网络请求失败”,它如下 xhr.onerror C:\Users\ratna\Downloads\New folder (9)\MealizeProject\node_modules \whatwg-fetch\dist\fetch.umd.js:473:29
    • 我现在将代码添加到问题中,spring boot URL 为 localhost:8080 并且数据库在谷歌云上,所以我使用了我的公共 IP
    【解决方案2】:

    谢谢大家,终于解决了代码中缺少返回的问题

     fetch('URL')
      .then((response) => {
        return response.json();
       })
      .then((responseData => {
        console.log(responseData);
       this.setState({ data: responseData });
         }))
    

    URL 的 localhost 部分是 IPv4,本地 Ip 和变量是 data:[ ]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多