I want to send data from web or local file to a html element by NodeJs/Express
here my pseudo code looks like
Grab data from src > parse the data > sent it to an element of index.html
app.get("/", (req,res) => {
const url = "https://asc.com"
https.get(url, (response) => {
response.on("data", (data) => {
const webData = response.on(JSON.parse(data));
const highestSoldCountry = webData.country;
const mostSoldModel = webData.car.model;
// I want to post/send data to an element
res.sendFile(__dirname + "/index.html", {webData: document.querySelector("h1")})
res.sendFile(__dirname + "/index.html", {highestSoldCountry: document.getElementById("web-data")})
res.sendFile(__dirname + "/index.html", {mostSoldModel: document.getElementsByClassName("car-data")})
});
});
});
Or is it possible to select a DOM element by Node/Express?
2
Answers
It is not possible to select a DOM element by Node/Express. DOM is in browser, while Node/Express run in a separate process(be it locally or a server).
Web developers do not see it as "sending data to a html element". They see it as "fetching data from server to update a html element".
I am assuming, you have a HTML page in browser in which you want to render the data that you collect from your Node/Express server.
From the HTML page, you need to make an AJAX call to your Node/Express server. It is HTTP request only, the difference is you will make the request using JavaScript.
Once you receive the data from server, you can convert that in to an element & append it into DOM.
Server:
Client(somewhere in your html page or in a JavaScript file which is added in the html file):
Hope this clarifies few things!
Here’s a corrected version of your code: