Patrik18
Patrik18

Reputation: 329

Can I run Nodejs JavaScript script in HTML document?

Is it possible to run this JavaScript code in .html document:

<script>
    function DBConnect() {
        var mysql = require('mysql');
        var mydb = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: 'admin123',
            database: 'users'
        });

        var username = user_name.value;
        mydb.connect();

        var query = ('select passwd from peer where username=' + username);

        console.log(query);

        connection.end(function(err) {
            // The connection is terminated now
        });
    }
</script>

Because when I'm trying always got an error: Undefined "require", or how can I call this function in other f.e.: db.js? I have already script server.js, that is running from Node.js, do you think the code above should be running here?

Upvotes: 0

Views: 10498

Answers (4)

Kevin Davies
Kevin Davies

Reputation: 41

Even if it was possible to connect to the MySQL database directly from the HTML, it is a bad idea. If you include the database credentials in the HTML, anyone who has access to that webpage can access your database and do whatever they want with it. This is a bad idea.

Upvotes: 2

MastErAldo
MastErAldo

Reputation: 664

You are probably trying to execute Node.js JavaScript code in a browser and the require keyword isn't recognized.

To import a JavaScript file in a browser, you should use something like this:

<script src="path/to/your/JavaScript/file"></script>

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

Using browserify, you can run some Node.js modules on the browser, but one doing such heavy I/O can't run in your browser.

So no, you can't simply take this Node.js code and try to run it in the browser. You'll have to design a proper client-server application, with the server doing all accesses to the database.

A solution for which you'd get many tutorials could for example be

  • To let your browser JavaScript code issue some Ajax requests
  • To let your server answer those requests by querying the database and send some data in JSON in the response.
  • To make the browser change the HTML using this JSON.

You could start by googling "json node.js ajax mysql", but you have a lot of study facing you.

Upvotes: 2

djechlin
djechlin

Reputation: 60748

Ignore everyone suggesting browserify. That would make sense if you had a basic understanding of the client-server architecture, and hence, had an intuition for the limitations of browserify. The answer to your question is

No.

Node.js code runs on the server. In your code you are doing things that cannot be done on the client. You should probably understand why before attempting to write code that handles sensitive information.

Upvotes: 4

Related Questions