I created a function that sends a get request for fav.json and assigned the id="fav_button" button to execute this function. Additionally, I configured an express server. However, upon clicking the button, only the last item in the json file is displayed. The fetched json file consists of an array of objects.
Various troubleshooting steps have been attempted, including using .send instead of .json or .sendFile, debugging the json file (with no issues found), and even attempting to utilize jquery instead – all with no success.
// script.js
function get_fav(e) {
if (!e) {
e = window.event;}
el = e.target || e.srcElement;
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
let list = JSON.parse(xhr.response);
for (var i in list) {
let hold = fav_tem;
hold = hold.replace('%title', list[i].song);
hold = hold.replace('%artist', list[i].artist);
hold = hold.replace('%mood', list[i].mood);
document.getElementById('faves_field').innerHTML = hold;}}};
xhr.open('GET', 'fav.json', true);
xhr.send();}
const fav_el = document.getElementById('fav_button');
if (fav_el.addEventListener) {
fav_el.addEventListener('click', get_fav, false);}
else {fav_el.onclick = get_fav;}...
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const fs = require('fs');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
res.send(fs.readFileSync('public/index.html'));
});
app.get('public/fav.json', function(req, res) {
res.json(fs.readFileSync('public/fav.json'));
});...
...app.listen(3003, function() {
console.log('Server started on port 3003...');
});
The purpose of my script is to fetch fav.json and display each object part in the blue boxes as follows: (in bold) Song - artist. Mood: mood(s). My application should listen for the request for public/fav.json and then send it.
However, despite following the outlined process, clicking the designated button results in only displaying the final object from the json file in the blue box below. If you wish to explore the full project (bearing in mind my limited web development experience), feel free to visit https://github.com/YungLonk/Practice-Node-JS. What could be lacking or incorrect in my approach?