skip to Main Content

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


  1. 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:

    app.get("/", (req, res) => {
    
      const url = "https://asc.com"
    
      https.get(url, (response) => {
    
        let content = '';
        response.on("data", (data) => {
          content += data;
        });
    
        response.on("end", () => {
          const webData = JSON.parse(content);
          res.json(webData);
        });
        
      })
    
    });
    

    Client(somewhere in your html page or in a JavaScript file which is added in the html file):

    async function displayWebdata() {
      const response = await fetch("http://your.node-express.server.url"); // <-- update this
      const webData = await response.json();
    
      // update the HTML using webData in the way you want
    
    }
    

    Hope this clarifies few things!

    Login or Signup to reply.
  2. Here’s a corrected version of your code:

    1. Create your index.html file in the same directory as your Node.js script with placeholders for dynamic content. Here’s an example index.html:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Web Data Display</title>
    </head>
    <body>
        <h1 id="webDataPlaceholder">Web Data Placeholder</h1>
        <p id="countryPlaceholder">Country Placeholder</p>
        <p class="carDataPlaceholder">Car Model Placeholder</p>
    </body>
    </html>
    1. Now, let’s update your Node.js/Express code:
    const express = require("express");
    const https = require("https");
    const app = express();
    
    app.get("/", (req, res) => {
        const url = "https://asc.com";
    
        https.get(url, (response) => {
            let rawData = "";
            
            response.on("data", (chunk) => {
                rawData += chunk;
            });
    
            response.on("end", () => {
                try {
                    const webData = JSON.parse(rawData);
                    const highestSoldCountry = webData.country;
                    const mostSoldModel = webData.car.model;
    
                    res.send(`
                        <html>
                        <head>
                            <title>Web Data Display</title>
                        </head>
                        <body>
                            <h1 id="webDataPlaceholder">${webData}</h1>
                            <p id="countryPlaceholder">${highestSoldCountry}</p>
                            <p class="carDataPlaceholder">${mostSoldModel}</p>
                        </body>
                        </html>
                    `);
                } catch (error) {
                    console.error("Error parsing data:", error);
                    res.status(500).send("Error parsing data");
                }
            });
        });
    });
    
    app.listen(3000, () => {
        console.log("Server is running on port 3000");
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search