I'm new to node js. Is that possible to create a html dom element on front end(index.html) using node js. If I insert any data into DB means then I want to create an html dom element like "li" (list) to show the inserted data in my index.html file.
2 Answers
Creating a html dom element in an existing html document is possible with javascript and whatever is your backend. You just use document.createElement() or whith jquery $('mytag').append('newTag). You can send JSON or (XML) from your server: res.json({foo: 'bar') with expressjs for example. Then from the client you make an AJAJ (AJAX) call to the route of your backend. I think what you are trying to do is a Single Page Application.
1 Comment
Create as Text on Node Server
The easiest way to do this is to create a html-string of the desired elements and send it to the client. You can inject your new Dom-Elements in the HTML String. You have to make a new request each time you want to regenerate your Dom-Element Tree from the server.
const http = require("http");
const host = 'localhost';
const port = 8000;
const responseText = `<ul>
<li>First</li>
<li>Second: ${'inserted Data'}</li>
<ul>`;
const requestListener = function (req, res) {
res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.end(responseText);
};
const server = http.createServer(requestListener);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});