can't import mysql in node.js - javascript

I didn't expect that I'll stuck with this simple (at first glance) question, but I really haven't find anything helpful about the problem. I use the following code in my connect.js file:
`let mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'xxxxx',
password: 'xxxxxxxxxxxxxxx',
database: 'xxxxx'
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
`
then I run the following command, and recieve this response:
` $ node connect.js
file:///home/timothy/Desktop/Backend/connect.js:1
let mysql = require('mysql');
^
ReferenceError: require is not defined
at file:///home/timothy/Desktop/Backend/connect.js:1:13
at ModuleJob.run (internal/modules/esm/module_job.js:145:37)
at async Loader.import (internal/modules/esm/loader.js:182:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)`
I tried to remove 'type': 'module' from my package.json file, then it works as intended, I recieve console.error (but that is not the point, it's related to my database). But if I remove 'type': 'module' my main file index.js doesn't work, because it uses express js dependency. So now I wondering how to make both files work properly. I tried to install requirejs via
`$ npm i requirejs
`
but it doesn't solve my problem
UPDATE:
mysql npm package is installed of course
and I see the same problem here:
How can I get all the filesnames from a directory on the server in javascript?
Many people says that this error happens when you try running code in a browser and not in a nodejs server. I don't know if I have to specify that this file is for node server. I just run
node filename.js
As you can see, may be I miss something?

Can you try to change to this
import * as mysql from 'mysql'
or
import mysql from 'mysql'
And set type to module

I think your mysql npm package is not installed or an unwanted character put before
let mysql = require('mysql'); line, so at first run npm i mysql command on your project directory. then use the following code...
let mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'ecomm'
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});

Related

I can't access to mySQL with node js anymore

I have updated my node version, and now I can't access to my DB with my app. I tried many things:
-Change rout to 127.0.0.1.
-add my port number 3306
-add socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
-kill node running
And probably others, but I always have an error. Actually, I have this one while running this code.
Error:
disconnected
error: connect ECONNREFUSED ::1:3306
My code who was working before:
const mysql = require('mysql');
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "discord"
});
if (db.state === 'disconnected') {
db.connect(function (err) {
if (err) { return console.error('error: ' + err.message); }
console.log('Connected to the MySQL server.');
});
}
console.log(db.state);
module.exports = db
My issue was the version of discord.js because I have updated it as well. I've changed it in my package.json for the one I used before and everything is working well. It will be hard to update all my app to the new version. If you have any recommendation to update it easily without running into multiple issues, I'm here !

Error: read ECONNRESET when connected to a mysql server with Node.js

I'm trying to establish a simple connection to my database with the mysql npm package. At first glance, everything works fine and I can get the information I need, however, if I leave the server running for some time I get the following error:
Error: read ECONNRESET
at TCP.onStreamRead
const express = require('express');
const app = express();`
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'XXXX.mysql.database.azure.com',
user: 'XXXXX',
password: 'XXXXX',
database: 'XXXXX'
})
db.connect((err)=>{
if(err){
console.log(err.message);
} else {
console.log('Connected to the database');
}
})
As far as I understand the problem stems from the database connection being in idle mode. Do I need to configure the Azure server or is there something else I need to do?
Couple of things to try:
You can try creating connection pool instead of **createConnection**
mysql.createPool({});
Modify your package.json like below:
"dependencies": {
"mysql": "git://github.com/mysqljs/mysql#e3e123e9af7c0829a6c1417d911572a75b4a5f95"
},
It is described in detail here:
Bad handshake or ECONNRESET Azure Mysql Nodejs
https://social.msdn.microsoft.com/Forums/en-US/c8fedbcc-909d-41ce-8c72-0374f76fdf82/cannot-connect-from-nodejs?forum=AzureDatabaseforMySQL
Hope it helps.

node.js - Can't connect to MYSQL database with Sequelize

I'm starting at Node.js and i'm trying to make a simple connection with Sequelize based on its documentation (http://docs.sequelizejs.com/manual/installation/getting-started.html#installation).
Here my db.js file :
const Sequelize = require('sequelize')
const db = new Sequelize('chat','root','root',{
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
db
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
When executing this code, I have no success nor error message, just a message indicating 'String base operators deprecated' but nothing important i think.
I tried changing localhost to 127.0.0.1, remove port number and multiples thread but i'm stucked here...
Tested your code and all seemed to work fine, it connected successfully to the database instance I have running.
You might want to ensure mysql2 package is installed. Also check that the database chat has been created in MySQL workbench, and ensure the password is correct.

Connecting to MySQL on Node.js not initialized

I can't connect to the MySQL-database. I've googled some solutions, but none seems to work, or perhaps I haven't understood them. This is the setup:
let express = require("express");
let mysql = require("mysql");
let http = require("http");
let app = express();
http.createServer(app).listen(8000, function() {
console.log("Listening on http://localhost:" + port)
});
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: process.env.DB_PASSWORD,
database: "users",
port: 8000
});
connection.connect();
connection.query("SELECT * FROM user", function(err, rows, fields)
{
if (err) {
console.error("error connecting: " + err.stack);
return;
}
console.log(rows[0]);
});
connection.end();
Tried to setup the connection with "socketPath" and with another port, but they both returned error:
Error: connect ECONNREFUSED 127.0.0.1:3306
at Object.exports._errnoException (util.js:1034:11)
at exports._exceptionWithHostPort (util.js:1057:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1099:14)
--------------------
at Protocol._enqueue (/vagrant/node_modules/mysql/lib/protocol/Protocol.js:141:48)
at Protocol.handshake (/vagrant/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/vagrant/node_modules/mysql/lib/Connection.js:130:18)
at Object.<anonymous> (/vagrant/app.js:12:12)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
When the connection and listen listens on same port, it doesn't return any errors, but the connection doesn't seem to initialize.
console.log(connection.connect()); // -> undefined
I'm very new to using MySQL to node so I'm probably doing this all wrong, but can't figure out what the problem is
For MAC users using MAMP
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "databasename",
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
socketPath points to MAMP "mysql.sock" to permit the NodeJS/Mysql connection.
NOTE: the above connection also solves "Error: connect ECONNREFUSED 127.0.0.1:3306".
I hope this helps someone.
Change your connection.connect() to
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
so you can see errors.
EDIT:
Check bind-address and port in mysql config file (/etc/mysql/my.cnf). If your mysql server is running on host environment and node is running in guest (any virtualization like docker), set mysql server to listen on your local ip (eth0 like 192.168.0.x) and use same address in node config
As it turns out, I was a bit stupid. I was running the application on a Vagrant-server(virtual server), and I was trying to connect to my local-server. As soon as I tried to connect to the vagrant-server, everything worked properly. I also didn't have mysql-server properly installed to my vagrant machine.
if you don't set the port or set it to mysql default port i.e 3306 it works fine.
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "mysqluser",
password: 'password',
database: "yourdatabase"
});
I don't know the exact cause(although i tried with different ports), why it's not running on different ports but here is a link that shows how to use different port number for connecting mysql.
FYI: You are setting your app to run on 8000 and again the port mysql
using in your app is 8000.You must change it to something else.
You have to set socketPath and before you run your script make sure your MAMP is running or not.
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
Remove your port key value(port: 8000) and socketPath if you added,
from sql configuration, and try.
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "root",
database: "users"
});
Actually you occupied 8000 port by node server so you can't assign same port to different process.
Second mysql is running on port 3306. so you could not connect mysql through different port.
You can use different port for mysql but by some proxy pass mechanism or by running mysql itself on specific port.
Please follow simple steps to start (Worked on windows Machine):
Download and install MySQL from following link click here.
Configure downloaded file (I had kept default config parameters). Please check this video link for reference
Make sure MySQL server status is on.
Now you can check connection status by using below node code.
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
port: 3306
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL Server');
})
Start Your Mysql Server from your Xampp Control panel

What is the correct way to retrieve data from database using nodejs and MySQL?

I've written a code that should retrieve data from database with nodejs and mysql but it's not working.
It says the I didn't installed the mysql module but I did, using npm install:
The proof that I installed the mysql module successfully:
Is my code ok ? Keep in mind that I'm completely new to node.js.
var http = require('http');
http.createServer(function(request, response){
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('My first node server...');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost:8888',
user : 'root',
password: '',
database: 'test'
});
connection.connect();
connection.query('SELECT * FROM tabel_test', function(err, rows, fields){
if (!err) {
console.log('The result is ', rows);
} else {
console.log('No results.');
}
});
connection.end();
response.end();
}).listen(8888);
The code seems fine, the exception says that you do not have the mysql module, that could be technically true.
Make sure you have the node_modules\mysql folder in the current working directory, or that you have installed it globally with npm install -g mysql.
By the way I suggested the package.json file, because in there you could define the required version of the mysql module. Then if you do npm intall in the folder, the enumerated dependencies will be downloaded to the current working directory. This also make it easier for others to use you code, if you put it into a git repository.
if you found the given path node/node_modules/mysql/lib
change the below line
connection.query('SELECT * FROM test_user', function(err, rows, fields)
connection.end();

Categories