0

My use case or problem arising might be simple. I am not able to debug or figure out why my request is logging Pending promise. Let me kick in all relevant code and we can talk then

index.html

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Infinite Scroll</title>
    <script src="./infiniteScroll.js" defer></script>
  </head>
  <body>
    <div id="testimonial-container"></div>
  </body>
</html>

infiniteScroll.js

async function fetchAndAppendTestimonials(limit = 5, after = 0) {
  const testimonialsResponse = await fetch('/testimonials');
  const testimonials = testimonialsResponse.json();
  console.log(testimonials);
}
fetchAndAppendTestimonials(5, 0);

I starting adding server.js incrementally so that I can bypass CORS to call the external API - 'https://api.frontendexpert.io/api/fe/testimonials';

server.js

const express = require('express');
const cors = require('cors');
const path = require('path');
const axios = require('axios');

const app = express();
const port = process.env.PORT || 80;
app.use(cors());
app.use(express.static('public'));
const API_BASE_URL = 'https://api.frontendexpert.io/api/fe/testimonials';

async function fetchTestimonials(limit = 5, after = 0) {
  const testimonialUrl = new URL(API_BASE_URL);
  testimonialUrl.searchParams.set('limit', limit);
  testimonialUrl.searchParams.set('after', after);
  try {
    const testimonials = await axios.get(API_BASE_URL);
    return testimonials.data;
  } catch (error) {
    console.log(error);
    return error;
  }
}
app.get('/testimonials', function (req, res) {
  const testimonials = fetchTestimonials(5, 0);
  console.log('testimonials', testimonials);
  res.json(testimonials);
});
app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, '/index.html'));
});

app.listen(port, function () {
  console.log('Server is running on port', port);
});

This is the entire app (w/o package.json and other meta files) so far and what I don't understand is that inside server.js file and fetchTestimonials function, the testimonials returned are Promise { <pending> }. This is evident from the console.log I have after the function call.

Can anyone correct this so that I can return a JSON response back to my client side infiniteScroll.js file?

Tangential but if someone, could add if this is the best approach to allow CORS would be great.

HalfWebDev
  • 7,022
  • 12
  • 65
  • 103

1 Answers1

0

You don't seem to be awaiting fetchTestimonials inside your /testimonials route. By making your route handler async, you can solve the Promise {<pending>}

app.get('/testimonials', async function (req, res) {
  try {
    const testimonials = await fetchTestimonials(5, 0);
    console.log('testimonials', testimonials);
    res.json(testimonials);
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
});
Raghav Kukreti
  • 552
  • 5
  • 18
  • Hey Raghav, thanks. This seems to be the miss. However, on making this fix, I am getting an error - https://stackoverflow.com/questions/27101240/typeerror-converting-circular-structure-to-json-in-nodejs On commenting `res.json` in my file, code logs without any errors. Also, API response is returning zero testimonials if I compare it to hitting on browsers. Would you have any idea about it? – HalfWebDev Feb 18 '23 at 15:03
  • For the issue of the API returning zero testimonials, try making a request to the API using a tool like Postman to see what the response looks like outside of your app. And on `res.json` emitting the circular reference error, does the object reference itself directly/indirectly? If you cold paste the structure of your data somewhere, it could help. – Raghav Kukreti Feb 18 '23 at 15:10
  • Ok. Fixed this by returning `testimonials.data` from `fetchTestimonials` function. On client script, this is logging raw HTTP response and NOT `hasNext: true, testimonials: []`. Raw HTTP response is similar to the log you will get when we don't do response.json() on a promise. – HalfWebDev Feb 18 '23 at 15:11
  • Raghav, for structure of data, you can actually try hitting that API mentioned in browser. I will check in POSTMAN too – HalfWebDev Feb 18 '23 at 15:12
  • Glad to hear! If the above answer helped solve your earlier issue, could you mark it as accepted? – Raghav Kukreti Feb 18 '23 at 15:13
  • Postman returns the response in the same way browser does. No problems there. Surprised how app is reacting to it. It has zero testimonials array. Secondly, I cannot see the results on client, which is the end goal to render data – HalfWebDev Feb 18 '23 at 15:14
  • Yeah, I can see it's empty. I am not too aware of the frontendexpert API but it should be populated if they're using it as part of a course or something – Raghav Kukreti Feb 18 '23 at 15:15
  • Maybe try using https://mockapi.io/ to mock an API, similary and filling with dummy data to verify if your application works? – Raghav Kukreti Feb 18 '23 at 15:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/251976/discussion-between-halfwebdev-and-raghav-kukreti). – HalfWebDev Feb 18 '23 at 15:17