Attempting to populate HTML content retrieved from my MySQL database

Currently, I am attempting to retrieve HTML content stored in my MySQL database using nodejs.

The products are being retrieved from the database successfully.

export async function getAllProducts() {
    try {
        const response = await fetch('http://localhost:4000/productos');
        
        if (!response.ok) {
            throw new Error(`Error: ${response.status} - ${response.statusText}`);
        }

        const json = await response.json();
        return json;
    } catch (error) {
        console.error('Error fetching products:', error.message);
        throw error;
    }
}

However, when trying to insert it into the HTML, I encounter this error:

import { getAllProducts } from "../products.js"

//instances
const burger_container = document.getElementById("burger-container");
const smash_container = document.getElementById("smash-container");
const salad_container = document.getElementById("salad-container");
const drink_container = document.getElementById("drink-container");

const fillProducts = async () => {
    const products = await getAllProducts();

    products.forEach(product => {
        const category = product.category;

        let container;

        // Directly comparing with strings
        if (category === "hamburguesa") {
            container = burger_container;
        } else if (category === "smash") {
            container = smash_container;
        } else if (category === "ensalada") {
            container = salad_container;
        } else if (category === "bebida") {
            container = drink_container;
        }

        // Creating element within the category 
        if (container) {
            container.innerHTML += `<div>${product.name}</div>`;
        }
    });
}

Please assist me with this issue :)

I am endeavoring to fetch the products from the database and display them in the HTML using container.innerHTML.

Answer №1

give this a shot.

const fetchData = async () => {
    // Implement your logic here
}
module.exports = fetchData;

const fetchData = require("./data.js");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to analyze the array?

<?php $username = "trainerapp"; $password = "password"; $hostname = "localhost"; $link = @mysql_connect($hostname, $username, $password); if (@mysql_select_db("trainer_registration")) { $select_query_num = @mysql_query("select id from program_d ...

Finding the correct column in a drop-down menu based on a table array using AngularJS

In my controller, I have data like this: $scope.operationData = [ { "label" : "Inventory", "labelType" : "Master Tables", "type" : "PROCESSOR", "outputStreams" : 1, "elementType" : "TABLE", "name" : ...

Filter JavaScript elements by conditions and true/false values

I can't quite recall the answer to this at the moment. Consider an array of Vendors (this is just placeholder data): [ { "user_updated": null, "user_created": "128a84b5-275c-4f00-942e-e8ba6d85c60e", "d ...

Mongoose and the concept of floating point values

My latitude and longitude numbers are being converted to strings. However, my section integers remain as the correct data type of Number. How can I adjust my model to retrieve lat and lng as Float instead of String? I am storing latLng data in my database ...

The sticky header is malfunctioning due to a null offsetTop value

import React , {useRef, useEffect} from 'react' import './header.css' const nav_links =[ { path:'#home', display:'Home' }, { path:'#about', display:'About& ...

Utilize custom parameter binding in nestjs and routing-controllers for expressing GET and POST requests

In my Controller using nestjs / routing-controllers, I am handling a GET request like this: /collect?t=My-name The parameter t represents a full name that cannot be changed. Below, by injecting @QueryParams() data: CollectData, I am trying to find a way ...

Delay the v-alert display after an item is added to the array basket using setTimeout

here is my custom rightTableMenu template <template> <div> <h1 align="center">{{ title }}</h1> <v-alert type="info" icon="mdi-emoticon-sad" v-if="basketStatus"> Empty Basket, please add some to basket < ...

What are the possibilities for modifying a MySQL database using HTML?

Currently, I have a MySQL database managed through phpmyadmin that I would like to present as an HTML table for easy editing of records and columns directly. I am unsure about the terminology to use when researching possible solutions. What options are av ...

Steer clear of including optional dependencies when using Yarn for package installations

Within my yarn.lock file, there is a single reference to momentjs: pikaday@^1.6.0: version "1.6.1" resolved "https://registry.yarnpkg.com/pikaday/-/pikaday-1.6.1.tgz#b91bcb9b8539cedd8dd6d08e4e7465e12095671b0" optionalDependencies: moment "2.x" ...

Guide to direct express.js requests straight to 404 page

I need guidance on how to direct a request to a specific route in express.js directly to a 404 error page if the user is not authenticated. Currently, my middleware includes the following code: exports.isAuthenticated = function (req, res, next) { if ( ...

When utilizing the ExpressJS API to retrieve GET requests in C++, the response string can only be used for printing purposes and nothing else

Issue: I am currently working on a C++ program that interacts with an ExpressJS API to retrieve files and strings. While I have successfully managed to download text files using curlRequests, I am encountering difficulties when attempting to handle plain s ...

The Parse.com cloudcode refuses to enter the success or error state

Running this code in my Parse cloud, I noticed that when I call it from my app, it never enters the success or error statement. Could it be because the .save method isn't working? Any assistance would be greatly appreciated :) This is how I invoke t ...

Deleting a string by utilizing the Ternary operator in JavaScript

How do I remove the [object Object] from my output shown in the console? I'm looking to print the output without the [Object Object]. Is it possible to achieve this using a ternary operation? data:[object Object] text:Data is supplied by Government ...

What is causing my ajax request to malfunction?

I'm encountering an issue while trying to send a request using AJAX. The request is successful when I use the following webservice: https://jsonplaceholder.typicode.com/users However, when I attempt to make the same request with my own service, I fac ...

Changing the background of one div by dragging and dropping a colored div using jQuery

Looking at my HTML code, I have 4 <div> elements - 2 represent doors and 2 represent colors based on their respective id attributes. My goal is to enable users to drag any color to either door (e.g. blue on the left door and black on the right) and ...

Avoiding server requests in Firefox by refraining from using ajax

I've implemented the following jquery code: $("#tasksViewType").selectBox().change( function (){ var userId = $('#hiddenUserId').val(); var viewTypeId = $("#tasksViewType").val(); $.post('updateViewType& ...

An issue arises with ReactJS MaterialUI Stepper when there is an overflow

My struggle with the Material UI Stepper component persists as I attempt to make it suit my requirements, specifically to display multiple steps and handle overflow. However, it stubbornly continues to misbehave by showing unusual separators when there is ...

Storing a component in browser storage using JavaScript and Angular

I am currently working on developing an Angular application that allows users to "favorite" a business card and store it in local memory. I am facing challenges with actually storing the clicked element in the browser's local memory. Furthermore, I f ...

Combining SELECT queries for merging similar results in a non-DISTINCT result set

---------- ---------- ---------- ---------- | t1 | | t2 | | t3 | | t4 | ---------- ---------- ---------- ---------- | id | | id | | id | | t1_id | | foo | | bar | | foobar | | t2_id ...

In Javascript, merge two objects while maintaining their original references

Here's a basic illustration of my goal: data = {name: 'fred'}; newData = {}; newData.name = data.name; newData.name = 'ted'; console.log(data.name); // I expect this to be ted instead of fred I am wondering if it is feasible i ...