2

How to add data from an input field in the browser to my array websites[name], and then display it in a html paragraph?

server.js

import express from "express"
import { websites } from "./websites.js"
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import * as http from 'http'

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const server = express();

server.use(express.json());

server.get("/last", (req,res) =>{
    res.sendFile("index.html", {root: __dirname});
})

server.post("/last", (req,res) => {
    var DataG = req.body.name;
    http.get({host: DataG}, function(response){
    console.log(response.statusCode)
        if(response.statusCode < 400)
            console.log("server is up")
        else{
            console.log("server is down")
        }
    
    });
    
    res.send("Request processed"); 
})

index.html

<body>
    <center>
    <input class="text" placeholder="input website"> 
    <button class="subBtn">Submit</button><br><br>
    <div id="pisun"></div>
    </center>
    <script>
        let pisun = document.getElementById("pisun")
        let pisunchik1 = document.createElement("p").textContent = "nothing"
        let websiteName = document.querySelector(".text")
        let button = document.querySelector(".subBtn")
        if(button)
        {
            button.addEventListener("click", () =>{
                let obj = {
                    name:websiteName.value    
                };
                fetch("http://localhost:3000/last",{
                    method:"POST",
                    headers:{
                        "Content-type":"application/json"
                    },
                    body:JSON.stringify(obj)
                })
            })
        }
    </script>
</body>

websites.js ("db")

export const websites = [
    {name:"google", enable: true},
    {name:"bing", enable: true},
];
3
  • 1
    1. You are ending the post request before the http.get inside is finished. 2. What do you want to display and where? Commented Oct 29 at 13:06
  • First, I want to save everything I receive from the input field into an array in website.js. Then, I want to display it in the HTML file in paragraph format Commented Oct 29 at 13:19
  • If you want to modify local files, I would go with JSON format - easy to parse and serialize. Then you need to modify the actual file - see for example stackoverflow.com/questions/10685998/… . Then you need to return the actual HTML string, but I hope you are aware, that html is just a part of a website - there is also css and js. If you want to display a website inside your website, have you considered an iframe: developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/… ? Commented Oct 30 at 9:02

1 Answer 1

1

The first step to solve your problem is to implement some kind of saving. A simple yet stable solution is to utilize the Node's filesystem API. Instead of storing your websites in a variable (which makes them refresh with every session), you should modify the file. As it was already pointed out in the comments, JSON is a good starter for such things. Here is my code (for the sake of simplicity, I used the synchronous variants, you can replace them with async + callback if you wish):

import fs from "fs";

function getWebsites() {
    // Open the file and read the content
    const data = fs.readFileSync("./websites.json", "utf-8");
    return JSON.parse(data);
}

function updateWebsites(name) {
    const content = getWebsites();
    content.websites.push({ name: name, enable: true });
    // Write the modified data and close the file
    fs.writeFileSync("./websites.json", JSON.stringify(content));
}

server.post("/last", (req, res) => {
    var DataG = req.body.name;
    updateWebsites(DataG);
    // ...
}

Later you can implement some kind of caching to prevent redundant calls of readFileSync() until something has changed. Moving on to the second part of your idea: you can modify the HTML file with each website list update, but a way more typical way to reflect the data state is to add another endpoint to your server:

server.get("/sites", (req, res) => {
    res.statusCode = 200;
    res.send(getWebsites());
});

Having this set up, the only thing you have to do from your client is to query the list:

<script>
    async function displaySites() {

        const res = await fetch("http://localhost:3000/sites");
        const data = await res.json();
        const container = document.getElementById("somecontainer");

        data.websites.forEach(el => {
            const paragraph = document.createElement("p");
            paragraph.innerText = el.name;
            container.appendChild(paragraph);
        });
    }
</script>
<button onclick="displaySites()" id="req-btn">Display websites</button>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.