简体   繁体   中英

Node.js can't access lexical declaration 'x' before initialization and global variable problem

i'm having a problem with node.js app that i'm making. It's my first time using node.js so I knew there will be problems but so far I wasn't able to solve this one. I want to run a script after clicking an button on the site but I get can't access lexical declaration 'log' before initialization error and I think it is because I'm using global variable because the console is also displaying this error message require is not defined .

there's the code for script I export:

let login 
{
    login: Cat;
    haslo: 123;
}

function Logowanie(x, y){
    
        if (x == login.login && y == login.haslo){
            const zmianaTla = document.getElementById('overlay');
            const udanyLogin = document.getElementById('logon');
            zmianaTla.classList.remove('active');
            udanyLogin.remove();
        }
       else
            alert("Niepoprawny login lub haslo");
}
    

module.exports = new Logowanie;

the main script:

const log=require('./login.js');

x=document.getElementById('login').value;
y=document.getElementById('haslo').value; 

log(x, y)

And html part:

<script src="script.js"></script>
<div class="logon" id="logon">
     <h1>Logowanie</h1>
      <label for="Log"><b>Login</b></label>
       <input type="text" id="login" name="login" required>
            <label for="Haslo"><b>Hasło</b></label>
            <input type="password" id="haslo" name="haslo" required>
            <button type="submit" class="b1" onClick="log()"> Login </button>
    </div>
    <div class="active" id="overlay"></div>

I tried to fix it using solutions to the similar problesm other users had but they didn't work so I finally decided to ask for help myself.

I might be miss-understanding you here, so apologies if so, but maybe this is some help.

OK, are you running this in your browser, or using Node.JS (say via your command line)?

Because calls like document.getElement are browser specific I believe. Potentially that is why you are having require is not defined error. require is not implemented in browsers, only on Node.JS. Browser module syntax is different I think.

Maybe this article could help on the differences between Node.JS and JS in browser

Secondly, I think an't access lexical declaration 'log' before initialization error is going to be caused by using module exports incorrectly.

Your login.js file probably needs too change module.exports = new Logowanie; to module.exports = Logowanie; Pretty sure the new keyword is only for instantiating classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM