'How to Update HTML using Node JS from MYSQL

Question

How can i change my HTML data in the files via node JS i am not using EJS or any view engine I have a views folders where all the files are .js files returning HTML how can i change the data from the node server which selects the MYSQL data for example if i have

I have tried using res.send but it changes the whole file how can i change for example on the about page /aboutus

<h1 id='name'></h1>

How can i add data from the server to edit that file? thanks

For those who can't quite understand what i am saying is i have a server side which is meant to retrieve an html name for example david and i have a views folder containing js files like home.js which returns html value to the index.html file i want to change the heading tag in html like the code above i want 'David' to be put in the h1 tag



Solution 1:[1]

I have not been able to understand perfectly what you want to do ... But I believe that in any case to create a dynamic client server infrastructure you could use two methods:

  • by creating an endpoint that returns the data in json or xml format from the database, and replacing your DOM elements with the real data

example:

Express Backend example


app.get('/api/user', async function(req, res) {
 const userdata = await getUserData()
  res.send(JSON.stringify(userdata));
});


Front end example:

fetch('http://MYAPI.com/api/user')
  .then(response => response.json())
  .then(data =>{
    document.getElementById("username").innerHTML = data.username;
    document.getElementById("email").innerHTML = data.email;
});



  • by converting your html files into handlebars (for example) and replacing the handlebars tags with real data, then return html ready to be rendered.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1