Can't connect to mysql using node express - mysql

I'm trying to connect to mysql using express but I cannot get it to work. I've searched similar questions but couldn't find the correct one for me. Right know I have this simple code:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: ''
});
connection.connect((err) => {
if(err) {
console.log(err);
} else {
console.log("Connected");
}
});
var authRouter = require('./routes/login');
var homeRouter = require('./routes/home');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.use('/', authRouter);
app.use('/', homeRouter);
app.listen(3000, () => {
console.log("Running on port 3000");
})
I simply installed mysql using npm and tried to run the code. I keep getting Error: Connection lost: The server closed the connection.
It doesn't even log the error on const connection = mysql.createConnection
Tried using XAMPP but I get the same error.
Any help would be really appreciated, thanks!

Related

Getting PROTOCOL_PACKETS_OUT_OF_ORDER in MySQL Node.js connection

I am an absolute newbie to Node.js. I am trying to create a MySQL database and connect it to a node.js server and build APIs.
Here's my db.config.js:
const mysql = require('mysql');
//local mysql db connection
const dbConn = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'node_mysql_crud_db'
});
dbConn.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
module.exports = dbConn;
And here's my server.js:
const express = require('express');
const bodyParser = require('body-parser');
// create express app
const app = express();
// Setup server port
const port = process.env.PORT || 3306;
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse requests of content-type - application/json
app.use(bodyParser.json())
// define a root route
app.get('/', (req, res) => {
res.send("Hello World");
});
// Require employee routes
const employeeRoutes = require('./src/routes/employee.routes')
// using as middleware
app.use('/api/v1/employees', employeeRoutes)
// listen for requests
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
When I run nodemon server, I get the following error:
/Users/mac/Flutter_Projects/NodeMysqlCrudApp/config/db.config.js:12
if (err) throw err;
^
Error: Packets out of order. Got: 80 Expected: 0
code: 'PROTOCOL_PACKETS_OUT_OF_ORDER',
fatal: true
I have added max_allowed_packet=500M in my.cnf file and yet I continue to receive the error.
How to resolve this issue?

items does not add to mySQL Table

Do you know why I can not manually add the value "Sasan" to mySQL server?
MarioDB is installed in PHPStorm and schema is correctly selcted.
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mysql = require("mysql");
const cors = require("cors");
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "Test123456",
database: "shoppingList-DB"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get("/test", (req, res) => {
const sqlInsert = "INSERT INTO shoppingList (itemList) VALUES ('Sasan')";
db.query(sqlInsert, (error, result) => {
console.log("error", error);
console.log("result", result)
res.send("Hello Express");
})
})
app.listen(5001, () =>{
console.log("Server is up - Port 5001");
})
The error is pretty clear Access denied for user 'root'#'localhost'. Check your credentials and user access in mysql.user table.

Express taking forever to load mySQL query?

I'm trying to query a single line from a 28k record database as a test but it isn't going through but when I load up 'localhost:3001/api/get' it stays loading, even though my connection says success? Is it actually even connecting to the db?
my data bases schema is:
id | state_name | city
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get('/api/get', (req, res)=>{
const sqlGet = "SELECT city FROM state_city city = 'Chicago'";
db.query(sqlGet, (err, res)=>{
console.log("success");
});
});
app.listen(3001, ()=>{
console.log("running on port 3001");
});
First you must make server running. Remove that API route you had set before running server.
app.listen(3001, ()=>{
console.log("running on port 3001");
});
Now you must create database connection. Create new file dbconn.js
var mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
Now create new connection:
var new_connection = mysql.createPool(
db
);
new_connection.on('connection', function (connection) {
console.log('DB Connection established');
connection.on('error', function (err) {
console.error(new Date(), 'MySQL error', err.code);
});
connection.on('close', function (err) {
console.error(new Date(), 'MySQL close', err);
});
});
// export connection
module.exports = new_connection;
Include that connection in other file:
var db_connection = require('../dbconn');
db_connection.query(query, params, function (error, results, fields) {
//Do your query
});
Read about project structure to make your code easy to edit.

Cannot connect to SQL DB with Nodejs

I'm trying to connect to remote SQL server. I do connect from SQL Management Studio without problems, but with the code below i wait like 2-3 mins to get error ECONNRESET, what's wrong? Why do I wait so much?
let mysql = require('mysql'),
express = require('express'),
bodyParser = require('body-parser'),
app = new express(),
_port = process.env.port || 3000;
let con = mysql.createConnection({
host: '***.***.***.***',
port: ****,
user: "*****",
password: "****"
});
con.connect( function (err) {
if (err) console.log(err);
console.log('connected');
})
app.get('/', (req, res) => {
res.send('ffs');
});
app.listen(_port, () => {
console.log('listening on port ' + _port);
});
The mysql version is 2.11.0 atm, but i tried with the latest one first.

Internal error:TypeError: req.getConnection is not a function

Basically i am trying to connect to db using the below code and getting the error. Could someone help please?
Donno what needs to be done.
below is the code for app.js that i am using
app.js
var session = require('express-session');
var mysql = require('mysql');
var connection = require('express-session');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret:"ipsitatesting",
resave:false,
saveUninitialized:true,
rolling: true,
cookie: {
expires: 9 * 100000
}
}));
app.use(express.static(path.join(__dirname, 'public')));
// Create Sql Connection
app.use(connection(mysql, {
host: "localhost",
user: "root",
password: "ipsita123",
database: "project2",
},'request'));
app.use('/', index);
app.use('/users', users);
app.use('/login', function(req,res){
res.render('Calculator Login');
});
app.use('/logout', index);
Below is the code for index.js
index.js
//route for viewing products
router.post('/viewProducts', viewProducts);
function viewProducts(req, res, next){
//check if user has logged in
try {
var asin = req.body.asin;
req.getConnection(function(err, conn) {.... etc etc }