Connect Sequelize/Node to XAMPP Mysql - 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 :)

Related

pool.querty is not a function. Trying to connect google-cloud mysql instance from local machine

When trying to connect to the mysql instance on gcloud using nodejs and express. I'm getting the error "pool.query" is not a function. Bear with me since this the first time using gcloud and nodejs, i may be missing something obvious. I have already authorized my local ip,
This is my config
const config = {
user: process.env.DB_USER, // e.g. 'my-db-user'
password: process.env.DB_PASS, // e.g. 'my-db-password'
database: process.env.DB_NAME, // e.g. 'my-database'
socketPath: '/cloudsql/'+ process.env.INSTANCE_UNIX_SOCKET, // e.g. '/cloudsql/project:region:instance'
connectionLimit: 5,
connectTimeout: 10000, // 10 seconds
waitForConnections: true, // Default: true
queueLimit: 0, // Default: 0
};
module.exports = config;
This is my pool creation method
//dotenv
require('dotenv').config();
// import mysql2
const mysql = require('mysql2/promise');
// get config
const config = require("./config");
// Connect to database
// createUnixSocketPool initializes a Unix socket connection pool for
// a Cloud SQL instance of MySQL.
async function createUnixSocketPool() {
return mysql.createPool({...config,});
};
module.exports = {createUnixSocketPool};
And lastly my code for connecting
const path = require('path');
const express = require('express');
const { createUnixSocketPool } = require("./db");
const app = express();
// create mysql pool
const pool = createUnixSocketPool();
app.get('/',async (req,res) => {
console.log(await pool.query("show tables;"));
res.send("test");
});
// Listening
const PORT = process.env.PORT || 3000
app.listen(PORT, () => console.log('App is listening on port '+ PORT));
For some reason this says that pool.query doesn't exist? I'm very new to node.js and javascript in general, what am i missing?

Query a Google cloud SQL instance in Node.js from a GKE pod with cloud sql proxy running as sidecar

I am tasked with adding a MySql database to a microservice application for work. I am the only person on this task and don't really have anyone to turn too for advice so I am reaching out to the internets for help. I have succesfully deployed a pod that is running a small test application and the cloud-sql-proxy. I have scoured the documentation trying to figure out how to connect to the db and perform a query and this is what I have come up with (but it doesn't work).
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser')
const cors = require('cors');
const axios = require('axios');
const app = express();
app.use(bodyParser.json());
app.use(cors())
app.enable('trust proxy');
// Automatically parse request body as form data.
app.use(express.urlencoded({extended: false}));
// This middleware is available in Express v4.16.0 onwards
app.use(express.json());
// [START cloud_sql_mysql_mysql_create_tcp]
const createTcpPool = async config => {
// Extract host and port from socket address
const dbSocketAddr = process.env.DB_HOST.split(':');
// Establish a connection to the database
return mysql.createPool({
user: process.env.DB_USER, // e.g. 'my-db-user'
password: process.env.DB_PASS, // e.g. 'my-db-password'
database: process.env.DB_NAME, // e.g. 'my-database'
host: dbSocketAddr[0], // e.g. '127.0.0.1'
port: dbSocketAddr[1], // e.g. '3306'
// ... Specify additional properties here.
...config,
});
};
// [END cloud_sql_mysql_mysql_create_tcp]
var pool = createTcpPool();
const stuff = pool.query('SELECT * FROM entries');
function getQuery() {
console.log(stuff);
}
getQuery()
Here is a picture of the error I get when I deploy the pod and the logs from the proxy to verify it's running
I'm pretty new to MySql and GKE and trying to figure this out has been a huge struggle. I just want to know how I can actually query the db and would greatly appreciate some assistance or code sample to point me in the right direction, thanks internets.
As mentioned in the thread1 ,
Handling such functions can be done through following example :
const mysql = require('mysql');
const pool = mysql.createPool({ connectionLimit : 1, socketPath: '/cloudsql/' + '$PROJECT_ID:$REGION:$SPANNER_INSTANCE_NAME',
user: '$USER', p
assword: '$PASS',
database: '$DATABASE' });
exports.handler = function handler(req, res)
{ //using pool instead of creating connection with function call
pool.query(`SELECT * FROM table where id = ?`,
req.body.id, function (e, results) {
//made reply here
}); };
For more information you can refer to the documentation related to TCP connection when using Node js.
const createTcpPool = async config => {
// Extract host and port from socket address
const dbSocketAddr = process.env.DB_HOST.split(':');
// Establish a connection to the database
return mysql.createPool({
user: process.env.DB_USER, // e.g. 'my-db-user'
password: process.env.DB_PASS, // e.g. 'my-db-password'
database: process.env.DB_NAME, // e.g. 'my-database'
host: dbSocketAddr[0], // e.g. '127.0.0.1'
port: dbSocketAddr[1], // e.g. '3306'
// ... Specify additional properties here.
...config,
});
};
So trying to create a pool by calling createTcpPool seems to have been the issue. I changed it to
let pool = mysql.createPool({
user: process.env.DB_USER, // e.g. 'my-db-user'
password: process.env.DB_PASS, // e.g. 'my-db-password'
database: process.env.DB_NAME, // e.g. 'my-database'
host: '127.0.0.1', // e.g. '127.0.0.1'
port: '3306'
});
and got a succesful return from my db.

"Access denied for user localhost (using password: NO)" when I use variables from .env file

I'm losing my mind on this one. I have my app.js which creates a connection to mysql. It works fine like this :
app.js
const path = require('path')
const hbs = require('hbs')
const express = require('express')
const mysql = require('mysql')
const app = express()
const port = process.env.PORT || 3000
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "test"
});
db.connect((error) => {
if(error) throw error
console.log("MYSQL Connected")
})
But it doesn't work with this :
app.js
const path = require('path')
const hbs = require('hbs')
const express = require('express')
const dotenv = require('dotenv')
const mysql = require('mysql')
dotenv.config({ path: './.env' })
const app = express()
const port = process.env.PORT || 3000
const db = mysql.createConnection({
host: process.env.HOST,
user: process.env.USER,
password: process.env.PASSWORD,
database: process.env.DATABASE
});
db.connect((error) => {
if(error) throw error
console.log("MYSQL Connected")
})
.env
DATABASE = test
HOST = localhost
USER = root
PASSWORD = password
It recognizes the values I have stored in my .env file since my IDE is showing me the values when I type them in and as long the values of user & password are typed in app.js (but not host and database), it works.
I'm new to MySQL, never used it before, and I'm on Windows. So if I need to do some command lines, can you please specify in which terminal I should type them in ?
Can someone help me ?
Thank you !
Found the answer.
For some reason, this path :
dotenv.config({ path: './.env' })
Didn't work. I had to do it like this :
const path = require('path')
const dotenv = require('dotenv')
dotenv.config({ path: path.join(__dirname, './.env') })
I found this solution by using console.log() on the variables (process.env.HOST, etc...). They were undefined.
Conclusion : always console.log() your stuff.

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.

Error in connecting to Mysql from nodejs

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
});