Error in MySQL library for Node.js

In my Node.js application, I am trying to connect to a MySQL database hosted on Amazon.

$ npm install mysql 

My code looks something like this:

 var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'my amazon sql db', user : 'me', password : 'secret', database : 'my_db' }); connection.connect(); connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution); }); connection.end(); 

I can connect to my MySQL database using Workbench, so I'm sure my credentials are ok.

When I try to connect, I get the following error:

Connection.js: 91 Uncaught TypeError: Net.createConnection is not a function

Debugging code from the npm library - this is where the error occurs in connection.js :

 this._socket = (this.config.socketPath) ? Net.createConnection(this.config.socketPath) : Net.createConnection(this.config.port, this.config.host); 

connection.js has a dependency:

 var Net = require('net'); 

I am running Node.js locally on my windows machine.

Can someone tell me what might cause this error?

Separate ticket created: Error calling Node.js net.createConnection

+5
source share
1 answer

The net module, necessary and used in the MySQL node module, is the main part of Node.js. The error you get Net.createConnection , which is not a function, means that it appears as an empty object and the error is related to one of your comments on the question:

I am testing my code in a browser.

You should run this particular module only in Node.js, it cannot be run in a web browser.

You might think that you can run the code through a packer, such as browserify or webpack , so you can easily require('mysql') in your browser, but this will not work. The net module, which is the main dependency of the mysql module, will be converted to an empty {} object. This is not a mistake, how it should work. Browsers do not have common tcp implementations, so they cannot be emulated. An empty object is intended to prevent require('net') from failing from modules that otherwise work in the browser.

To avoid this error, you need to run this code in a clean Node.js environment, and not in a browser. A simple server can serve this purpose, since this code on your client in the browser cannot work and will add a hole to the security system, since all client parties are manipulating and, as such, are not protected. You do not want to disclose your database on the client side, but only consumes it.

+15
source

All Articles