Error in connecting to Mysql from nodejs - mysql

I have started node-js recently and i was trying to connect my nodejs server with mysql.
The problem is i am getting an error, i really don't know why, i am using phpmyadmin.
Phpmyadmin details
user: root
host: localhost
password is not set
This is the image of my phpmyadmin database
This is the settings of my phpmyadmin console
This is the terminal where it is showing error connecting to DB
index.js
var express = require("express");
var app = express();
var mysql = require('mysql');
var port = process.env.PORT || 3000;
var connection = mysql.createConnection({
host: "localhost",
user: "root",
database: "learning",
});
connection.connect(function(err){
if(err) {
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
console.log('3');
connection.end(function(err) {
console.log('Connection closed');
console.log('4');
process.exit();
});
});
app.listen(port,function(err1){
console.log("Listening on the port 3000");
});

connection to mysql from node js, you are use to mysql from node js connection
/config
/database.js
/server.js
/.env
const http = require('http');
const app = require('express')();
require('./config/database.js');
const bodyParser = require('body-parser');
const server = http.createServer(app);
server.listen(process.env.ServerPort, '0.0.0.0', () => {
logger.info(`Express server listening on port ${process.env.ServerPort}`);
});
When you run this:
node server.js
database.js file
const My = require('jm-ez-mysql');
// Init DB Connection
const connection = My.init({
host: process.env.DBHOST,
user: process.env.DBUSER,
password: process.env.DBPASSWORD,
database: process.env.DATABASE,
dateStrings: true,
charset: 'utf8mb4',
timezone: 'utc',
multipleStatements: true,
connectTimeout: 100 * 60 * 1000,
acquireTimeout: 100 * 60 * 1000,
timeout: 100 * 60 * 1000,
});
module.exports = {
connection,
};

I had changed the port from default 3306 of phpmyadmin mysql to 3308
therefore i added port: 3308 and it started working.
var connection = mysql.createConnection({
host: "localhost",
user: "root",
database: "learning",
port: 3308
});

Related

How to connect with mysql in config file?

What im trying to do is to connect MySQL database in my project in the config file.
config/db.js
const mysql = require('mysql')
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydatabase'
})
const connectDb = async () => {
const conn = await connection.connect(function (err) {
if (err) {
return console.error("error: ", err.message);
}
console.log("Connected to MySql server");
});
};
server.js
const connectDB = require("./config/db");
connectDB();
I have done this by fare and in my terminal is shown this error: TypeError: connectDb is not a function
How can I connect MySQL in the config file?
you'll need to export the connection verb, and delete the whole "connectDb" function
config/db.js
const mysql = require('mysql')
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydatabase'
})
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
server.js
const database = require("./config/db");
database.queryOrAnythignElse();
You'll probably want to learn again the basics of js and what is module.exports and etc...

JS code connection issues with postman ( connection error pops up says "EER_Socket_BAD_Port")

I am getting an error when I run this code, it says Port should be >= 0 and < 65536 and i sent 123456. how can i make my port smaller?
const mysql = require('mysql');
require('dotenv').config();
var connection = mysql.createConnection({
port: process.env.DB_PORT,
port: process.env.DB_HOST,
port: process.env.DB_USERNAME,
port: process.env.DB_PASSWORD,
database: process.env.DB_NAME
})
connection.connect((err) =>{
if (!err){
console.log("Connected");
}
else{
console.log(err);
}
});
module.exports = connection;

Why is this POST request failing from Postman?

Backend of my app is deployed on Heroku using Cleardb addon.
Below is the Backend code: For what I can tell it is hitting the POST requst.
const express = require('express');
const cors = require('cors');
//const mysql = require("mysql");
//this was the old way and did not support secure password
mysql = require('mysql2');
const app = express();
const port = process.env.PORT || 8000
/*
local connection
const db = mysql.createConnection({
connectionaLimit: 50,
user:'root',
host: 'localhost',
password:'',
database:'sys',
port: 3306
});
*/
const db = mysql.createConnection({
connectionaLimit: 120,
user: process.env.DB_USER,
host: process.env.DB_HOST,
password: process.env.DB_PASSWORD,
database: process.env.DATABASE,
port: 3306
});
app.use(cors());
app.use(express.urlencoded({extended: true}));
app.use(express.json());
//SQL connection test
db.connect((err) => {
if (err) console.error(err);
console.log('MySQL Connection Established.');
});
/* not used get request
app.get('/', (req,res) => {
res.header("Access-Control-Allow-Origin", "*");
res.send('Hello back');
}
);
*/
app.post('/' , (req,res) => {
const {email, name, question} = req.body;
res.header("Access-Control-Allow-Origin", "*");
console.log(`Your Email is ${email} and your name is ${name} and your ${question}`);
//MYSQL updating table
db.query("INSERT INTO customer_questions (name, email, question) VALUES (?,?,?)",
[name, email, question], (err,result)=> {
if (err) {
console.log(err)
}else {
res.send('data sent')
}
db.end();
}
);
});
app.listen(port);
console.log(`server is listing on ${port}`);
This is the error log. From what I can tell it the server runs and then stops and the post request hits status 500. I can tell why this is happening.
Post request using POSTMAN showing body.
Any help on this would be helpful. The MYSQL connection works both locally and through Heroku.
Use a connection pool and don't close the connection:
db.end();
You can run querys on the pool object and it will take care of opening/closing connections for you.

Connect Sequelize/Node to XAMPP Mysql

I've a working script to connect and work with Sequelize on Node.js
But now i'm trying to connect this to my MySQL database on XAMPP
MySQL Port on XAMPP: 3306
When i run node.js after i have configured the app.listen and the config of sequealize i get the following error
ERROR: listen EADDRINUSE :::3306
I've looked for but i didn't find much information about that, i don't know what i'm doing bad.
Thanks you for every answer!
app.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const { sequelize } = require('./models')
const config = require('./config/config')
const app = express()
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(cors())
require('./routes')(app)
sequelize.sync()
.then(() => {
app.listen(config.db.options.port || 3306) // 8081 original
console.log(`Server iniciado en puerto: ${config.db.options.port}`)
})
config.js
module.exports = {
db: {
database: process.env.DB_NAME || 'intraenvios',
user: process.env.DB_USER || 'root',
password: process.env.DB_PASS || '',
options: {
dialect: process.env.DIALECT || 'mysql', // sqlite original
host: process.env.HOST || 'localhost',
storage: './intraenvios.sqlite',
port: process.env.PORT || 3306 // 8081 original
}
}
}
EDIT:
For to connect by xampp simply, i made this:
const sequelize = new Sequelize('test', 'root', '', {
host: "127.0.0.1",
dialect : 'mysql',
operatorsAliases: false
});
sequelize.authenticate().then(function(){
console.log("sucess");
}).catch(function(error){
console.log("error: "+error);
});
Obs: operatorsAliases: false - To fix deprecated message of sequelize
Good Fun :)

Error when connecting to mysql in Mamp

I get this error when I try to connect to mysql database on phpmyadmin from nodejs . I am using same port number 3306 that is for mysql.After 4,5 seconds i get this error. I am using mamp free version for this .
connect ETIMEDOUT at Connection._handleConnectTimeout
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
//constants
const STATUS_SUCCESS = "success";
const STATUS_FAILURE = "failure";
mysql
var connection = mysql.createConnection({
host : '172.0.0.1',
user : '****',
password : '****',
database : 'parking_application'
});
connection.connect();
app.listen(4567,'localhost',function(){
console.log("server started");
});
Please Help.
Thanks in advance.
var mysql = require('mysql');
var connection = mysql.createConnection({
socketPath : '/Applications/MAMP/tmp/mysql/mysql.sock', //path to mysql sock in MAMP
user : 'userdb',
password : 'password',
host : '127.0.0.1',
database : 'yourdatabase'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting database ... nn");
}
Add the socket MAMP path to mysql (mysql.sock) in the json object connection.
Restart your server.
172.0.0.1. it's actually 127.0.0.1 or just use localhost