【问题标题】:How to pass data from Fetch API to index.html如何将数据从 Fetch API 传递到 index.html
【发布时间】:2021-02-08 03:17:30
【问题描述】:

我正在尝试将数据从 API 传递到我的网站。

我的目录:

项目> server.js |公开的

公共> index.html |样式.css

我的代码,它的一部分,在 server.js 中:

var link, txt; // I want to export these 2 variables to the website

fetch(`url`)
    .then(res => res.json())
    .then(body => {
     console.log(body); //receiving a json body and assigning data to both variables
     link = body.path;
     txt = body.path;
    })
    .catch(error => {
      console.log(error);
});

我没有找到任何方法来将它操作到 index.html 中,有什么好的建议吗?这可以通过 React 和 Node 实现吗?

在 React 的 App.js 中,我想要这样的东西:

<p>{link} or {text}</p>

我是网络开发新手,如果您能提供任何帮助,我们将不胜感激。

【问题讨论】:

    标签: html node.js reactjs express


    【解决方案1】:

    对于未来的人们,找到了一种使用 React (https://reactjs.org/) 和 Node express (https://nodejs.org/en/) 的方法。不知道这是否是最好的方法,但它对我有用:

    import React,{useState,useEffect} from 'react';
    import './App.css';
    
    function App() {
      
      const [data,setData]=useState([]);
    
      const [data1,setData1]=useState([]);
    
      const [data2,setData2]=useState([]);
    
    
      const getData=()=>{
            fetch(`url`)
            
            .then(function(response){
                console.log(response);
                return response.json();
            })
    
            .then(body => {
                 console.log(body);
                 setData(body.path); 
                 setData1(body.path);  
                 setData2(body.path);  
            })
    
            }
    
      useEffect(()=>{
                 getData()
       },[])
    
      
      return (
    
        <div className="App">
        
          <p>{data}</p>
          
          <p>{data1}</p>
    
          <p>{data2}</p>
    
          </a>
    
        </div>
    
      );
    
    }
    
    export default App;
    

    【讨论】:

      【解决方案2】:

      这在反应中会更容易,但也可以在纯 HTML 中完成。 您可以在前端获取数据并使用诸如 document.getElementById 之类的 DOM API 操作所需的 &lt;p&gt; 节点,并在您的获取承诺得到解决时更改 inner html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-17
        • 2017-06-22
        • 2017-04-29
        • 1970-01-01
        相关资源
        最近更新 更多