Home>

I am writing a site, the back of which is node.js , and the front is js , html , css . I learned how to run the node.js server, but I still haven't figured out how to combine it with client js. As I understand it, everything is written in one file, but what if I want to refer to the document object, and I get an error ReferenceError: document is not defined ?

Please tell me how to use this example to solve the issue of combining server and client javascript.

This is part of my index.html file:

<head>
    ...
    <script src= "../index.js"></script>
</head>
<body>
    <div class= "row">
        ...
        <input id= "email" type= "email" class= "validate">
        ...
    </div>
    <div class= "row">
        ...
        <input id= "password" type= "password" class= "validate">
        ...
    </div>
    <div class= "row">
        <a id="reg" class="waves-effect waves-light btn-small" href="main.html">Register </a>   </div>
</body>

This is part of my index.js file:

const http= require ('http')
const path= require ('path')
const server= http.createServer ((req, res)=>{
    let filePath= path.join (__ dirname, 'public', req.url=== '/'? 'index.html': req.url)
    //...
})
//Trying to get username and password from html and display them
const btn_reg= document.getElementById ('reg')
const input_email= document.getElementById ('email'). value
const input_pass= document.getElementById ('password'). value
btn_reg.addEventListener ('click', ()=>{
    console.log ("email:", input_email, "\ n", "password:", input_pass)
})
const PORT= process.env.PORT || 3000
server.listen (PORT, ()=>{
    console.log (`Server has been started on $ {PORT} ...`)
})

@entithat, and how in my case send a request from the client to the server? Through ajax?

Alex2021-02-23 18:30:16

document is not available in nodejs, at least the one you are trying to get. You need to include a separate js file in html and write logic there, and communicate with the server through requests

ThisMan2021-02-23 18:30:16
  • Answer # 1

    the document object is part of browser environment(this object is provided by javascript by the browser). a node.js is a server-side language (runs on server ( in the engine to be more precise) ) and, accordingly, it does not have this object. This is how you can send data from the form to the back:

    index.html

    &lt;
    ! DOCTYPE html &gt;
    &lt;
    html &gt;
        &lt;
    head &gt;
            &lt;
    meta charset= "utf-8" &gt;
            &lt;
    ! -there is no need to include index.js since the code inside it is executed by the node.js server and not by the browser. when you start it, you write node index.js so that the file is executed by node -&gt;
            &lt;
    script src= "../index.js" &gt;
    &lt;
    /script &gt;
     &lt;
    ! -don't do that -&gt;
        &lt;
    /head &gt;
        &lt;
    body &gt;
            &lt;
    ! -in action, specify the route by which we send data from the form. and we process this route in node -&gt;
            &lt;
    form action= "/save-user" method= "post" id= "reg-form" &gt;
                &lt;
    div class= "row" &gt;
                    &lt;
    input id= "email" name= "email" type= "email" class= "validate" &gt;
                &lt;
    /div &gt;
                &lt;
    div class= "row" &gt;
                    &lt;
    input id= "password" name= "password" type= "password" class= "validate" &gt;
                &lt;
    /div &gt;
                &lt;
    input type= "submit" id= "reg" class= "waves-effect waves-light btn-small" value= "Register" &gt;
            &lt;
    /form &gt;
        &lt;
    /body &gt;
    &lt;
    /html &gt;
    


    index.js

    let http= require ('http'),
        fs= require ('fs'),
        url= require ('url'), //to track the route
        {parse}= require ('querystring'); //to correctly take parameters from the request
    http.createServer (function (req, res) {
        if (req.url== '/' || req.url== '/index.js') {
            fs.readFile ('./index.html', function (err, data) {
                res.writeHead (200, {'Content-Type': 'text /html', 'Content-Length': data.length});
                res.write (data);
                res.end ();
            });
        }
        else if (req.url== '/save-user' &
    &
     req.method== 'POST') {//when something with the POST method "knocks" on the route '/save-user'
            let body= '';
            req.on ('data', chunk= &gt;
     {//when a piece of data "arrives". add them to the body
                body += chunk.toString ();
            });
            req.on ('end', ()= &gt;
     {//on completion of receiving a response. (when all the pieces of data have already arrived)
                let params= parse (body); //use the parse function from the querystring module
                //console.log (`email: $ {params.email} \ npassword: $ {params.password}`);
                res.end (JSON.stringify (params)); //convert string to json and return
            });
        }
    }). listen (8000);
    



    And if you need the client-side js to participate, you can send form via ajax request...
    As you can see, the "communication" between the back and the front can be carried out via "routes". you can NOT access the elements on the front directly from the back (like from the index.js file), just as you cannot directly access the back from the front. I advise you to read REST APIas with the way of communication between back and front.