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.