简体   繁体   中英

Fetching data from an API then sending it to an EJS file

I'm trying to send a json objectfetched with the fetch-api to an EJS file which loads when someone vists the website. The issue is I'm getting that the object sent is undefined by the time the page loads since it takes some time for the data to be fetched.

I could wrap the res.render with async and await to wait for the data to be fetched then render the page but this would slow down the website loading time. I want there to be a default value in the ejs file until the one from the api is fetched.

//One of the routes
router.get("/", (req, res) => {
fetchData(object => {
res.render("landingPage", { obj: object });
})

});

function fetchData(callback){
fetch("http://localhost:3000/api/teachers") //Could change this to a find request to the data base directly like Teacher.find()...
    .then(res => res.json())
    .then(res => {
      return callback(res);
    })
    .catch(err => {
      console.log(JSON.stringify(err));
    });
}
<!--In the HTML file-->
<h5><%= obj.someValue %></h5>

In the code I provided the server waits for the data to be fetched then renders the page. I want the page to load and when the fetching is done it adds the fetched object to the page. How could I do that?

In the code I provided the server waits for the data to be fetched then renders the page. I want the page to load and when the fetching is done it adds the fetched object to the page. How could I do that?

You can't, per se.

Your current implementation is akin to:

  1. Calling someone
  2. Asking them for information
  3. Being put on hold
  4. Them coming back and giving you the information

What you want would involve hanging up after step 2 so when they get back with the information, you're no longer there.


The closest you could come would be the return a document which includes some client-side JS which makes a second HTTP request for the data, and then modifies the DOM of the live page when it gets it.

This is generally known as Ajax. You can use fetch natively in modern browsers.

try this

router.get("/", async(req, res) => {
  const obj = await fetchData()
  res.render("landingPage", { obj });
});

function fetchData(){
  return fetch("http://localhost:3000/api/teachers")
      .then(res => res.json())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM