0

I am trying to pass data from an API to my website.

My directory:

project > server.js | public

public > index.html | styles.css

My code, a part of it, in 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);
});

I did not find any way to manipulate this into index.html, any good advice? is this possible through React and Node?

In App.js from React, I wanted something like:

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

I'm new in web dev, any help you can give would be greatly appreciated.

2 Answers 2

2

This would be easier in react, but it's also possible to do it in plain HTML. You can fetch the data on the frontend and manipulate the required <p> node using DOM APIs like document.getElementById and changing the inner html when your fetch promise is resolved

Sign up to request clarification or add additional context in comments.

Comments

0

For people from the future, found a way to do this with React (https://reactjs.org/) and Node express (https://nodejs.org/en/). Don't know if this is the best way, but it worked for me:

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.