Unable to connect to mySQL from Node.js - mysql

I am able to connect via the mySQL shell, but when I try from VS Code Nodemon crashes and i get the error.
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlMessage: "Access denied for user 'root'#'localhost' (using password: YES)",
sqlState: '28000',
fatal: true
My environment variable path is set up.
I have run... ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY '123456'
I have set up a new user, granted them full permissions and tried to connect to that user but still denied access.
//server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
var mysql = require('mysql');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456'
});
db.connect((err) => {
if(err){
console.log(err);
} else {
console.log('Connected');
}
})
app.listen('8000', () => console.log("Server running on port 8000"));```
package.json
{
"name": "mern-prac-2-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"cors": "^2.8.5",
"express": "^4.18.2",
"mysql": "^2.18.1",
"nodemon": "^2.0.20"
}
}
Thanks!
(edited)
Based on Juans Answer I have changed to this...
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const {Sequelize} = require('sequelize');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const sequelize = new Sequelize('fake_company', 'root', '123456', {
host: 'localhost',
dialect: 'mysql',
});
const tryConnection = async () => {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
tryConnection();
app.listen('8000', () => console.log("Server running on port 8000"));
And am having the error ...
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
sqlMessage: "Access denied for user 'root'#'localhost' (using password: YES)",
sql: undefined

I connect NodeJS con MySQL/MariaDB using sequelize package, this code is with typescript, you must change imports to require.
import { Sequelize } from 'sequelize';
// -----------------------------------------------------
const sequelize = new Sequelize('node', 'username', 'your-password', {
host: 'localhost',
dialect: 'mysql',
// logging: false
/* one of 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle' */
});
// -----------------------------------------------------
export default sequelize;
//------------------------------------------------------
// Then in the server I have this code.
import express, { Application } from 'express';
import cors from "cors";
import userRoutes from '../routes/usuario.mjs';
import sequelize from '../db/connection.mjs';
class Server {
private app: Application;
private port: string;
private apiPath ={
usuarios: '/api/usuarios'
}
// -----------------------------------------------------
constructor(){
this.app = express();
this.port = process.env.PORT || '8000';
// connect to DB
this.dbConnection();
// ...
}
// -----------------------------------------------------
// Connect with DB
async dbConnection(){
try {
await sequelize.authenticate();
console.log('Database is connected.');
} catch (error: any) {
throw new Error( error.message );
}
}
}
It works porperly for my.

If you want to use sequelize, I think you can create the perfect configuration with sequelize init commands. Sequelize gives you a config file in a configuration folder like below. You have to define a database for sequelize don't forget that.
Firstly you have to install npm install --save-dev sequelize-cli for your cli commands.Then you can use sequelize init command.
{
"development": {
"username": "root",
"password": "123456",
"database": "your db",
"host": "127.0.0.1",
"dialect": "mysql",
"query": {
"raw": true
},
"options": {
"pool": {
"max": 5,
"min": 0,
"acquire": 30000,
"idle": 10000
}
}
},
{
"development": {
"username": "root",
"password": "123124",
"database": "yourDB",
"host": "127.0.0.1",
"dialect": "mysql",
"query": {
"raw": true
},
"options": {
"pool": {
"max": 5,
"min": 0,
"acquire": 30000,
"idle": 10000
}
}
},

I think creating a new user and giving it privilege will help. The root user might need root access or administrative access. And node doesn't have a root access.

Related

Geeting RangeError [ERR_OUT_OF_RANGE]: The value of "sourceStart" is out of range. It must be <= 9. Received 13

I am trying to run the node using nodemon and am getting this error in the ubuntu server machine(20.0.2).
RangeError [ERR_OUT_OF_RANGE]: The value of "sourceStart" is out of range. It must be <= 9. Received 13
at new NodeError (node:internal/errors:372:5)
at _copy (node:buffer:235:11)
at Buffer.copy (node:buffer:776:12)
at Parser.parseBuffer (/home/ubuntu/cryztal_backend/node_modules/mysql/lib/protocol/Parser.js:272:16)
at HandshakeInitializationPacket.parse (/home/ubuntu/cryztal_backend/node_modules/mysql/lib/protocol/packets/HandshakeInitializationPacket.js:34:37)
at Protocol._parsePacket (/home/ubuntu/cryztal_backend/node_modules/mysql/lib/protocol/Protocol.js:272:12)
at Parser._parsePacket (/home/ubuntu/cryztal_backend/node_modules/mysql/lib/protocol/Parser.js:433:10)
at Parser.write (/home/ubuntu/cryztal_backend/node_modules/mysql/lib/protocol/Parser.js:43:10)
at Protocol.write (/home/ubuntu/cryztal_backend/node_modules/mysql/lib/protocol/Protocol.js:38:16)
at Socket. (/home/ubuntu/cryztal_backend/node_modules/mysql/lib/Connection.js:88:28) {
code: 'ERR_OUT_OF_RANGE'
}
[nodemon] app crashed - waiting for file changes before starting...
ormConfig
{
"type": "mysql",
"host": "localhost",
"port": 33060,
"username": "root",
"password": "root",
"database": "cryztal_dev",
"synchronize": true,
"logging": false,
"migrationsTableName": "migrations",
"entities": ["src/entity//*.ts"],
"migrations": ["src/migration//.ts"],
"subscribers": ["src/subscriber/**/.ts"],
"cli": {
"entitiesDir": "src/entity",
"migrationsDir": "src/migration",
"subscribersDir": "src/subscriber"
}
}
datasource.ts
export const AppDataSource = new DataSource({
type: 'mysql',
host: 'localhost',
port: 33060,
username: 'root',
password: 'root',
database: 'cryztal_dev',
synchronize: true,
logging: false,
entities: [
User,
PRIMARY.PARTNER.Partner,
PRIMARY.DEALS.Deals,
PRIMARY.ADMIN.Admin,
CATEGORY_MASTER.CategoryMaster,
PRIVACY.PrivacyPolicy,
SUBCATEGORY.SubCategoryMater,
],
migrations: [],
subscribers: [],
});
I was getting this error.
When I initially did the setup and while running the Nodejs.
The problem is I didn't create the DB which was configured in ORMconfig.js.
SO please make sure the DB setup is done correctly.

I'm using typescript and trying to create a connection using createConnection(({}).then(()); there are errors with .then

I am very new to macOS and I am following along to a course and I am stuck on trying to make a mysql connection.
The error I am getting is:
Property 'then' does not exist on type '{ type: string; host: string; port: number; username: string; password: string; database: string; entities: sting[]; logging: boolean; synchronizer: boolean; }'
import express from 'express';
import cors from 'cors';
import {routes} from "./routes";
import { createConnection } from 'net';
createConnection(({
type: "mysql",
host: "localhost",
port: 8000,
username: "admin",
password: "admin-1",
database: "FirstDB",
entities: [
"src/entity/*.ts"
],
logging: false,
synchronize: true,
}).then(() => {
const app = express();
app.use(express.json());
app.use(cors());
routes(app);
app.listen(8000, () => {
console.log('listening to port 8000')
});
}));

Typeorm pool doesn't exist in replication

typegraphql, typeorm, Mysql with master slave replication.
I have configured mysql with master and slave databases with separate instances and its working fine. I have encounter an error
while connecting via typeorm. Here's my ormconfig.json
{
"type": "mysql",
"logging": true,
"replication": {
"master":
{
"host": "192.168.0.250",
"port": 3306,
"username": "root",
"password": "test#123",
"database": "master",
"synchronize": true,
"extra": {
"connectionLimit": 5
}
}
,
"slaves": [
{
"host": "192.168.0.175",
"port": 3306,
"username": "root",
"password": "test#123",
"database": "master",
"synchronize": true,
"extra": {
"connectionLimit": 5
}
}
]
},
"entities": [
"src/entity/**/*.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
"subscribers": [
"src/subscriber/**/*.ts"
],
"cli": {
"entitiesDir": "src/entity",
"migrationsDir": "src/migration",
"subscribersDir": "src/subscriber"
}
}
My index.ts file with database connection as
import { gqSchema } from './schema';
import "reflect-metadata";
import { createConnection } from "typeorm";
import { ApolloServer } from "apollo-server";
async function main() {
await createConnection().then(async(res) => {
console.log(res)
console.log("Database Connected")
const schema = await gqSchema()
const server = new ApolloServer({
schema,
context: ({ req }: any) => ({ req })
})
await server.listen(4000)
console.log("Server has started!")
}).catch(err => {
console.log("err", err)
})
}
main();
And my resolver.ts file
#Resolver()
export class UserResolver {
/**
* query
*/
#Authorized()
#Query(() => User)
async hello(
#Arg("firstName") firstName: string,
): Promise<User | undefined > {
const slaveQueryRunner = getConnection().createQueryRunner("slave");
try {
const connection = getConnection().getRepository(User);
const usersList = await connection.createQueryBuilder()
.from(User, "user")
.setQueryRunner(slaveQueryRunner)
.where("user.firstName = ", {firstName})
.getOne();
console.log(usersList)
} finally {
slaveQueryRunner.release();
}
}
}

vscode debugger unexpected toke 'import'

I am new to nodejs and vscode...... I have two files: entry.js and /utils/database.js.
When I run node entry.js I get the little logging that I expect(SSSS). I would like to run this in debug mode so that I can build on it but when I click on the "Run" in debug on the left side I get:
SyntaxError: Unexpected token import
System: Ubuntu 18.04
Editor: Visual Studio Code version 1.45.1
node --version: v13.11.0
npm --version: 6.13.7
package.json:
{
"type": "module",
"name": "node_load_test",
"version": "1.0.0",
"description": "",
"main": "entry.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"mysql": "^2.18.1"
}
}
launch.json:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch root Program",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}/entry.js"
},
{
"type": "node",
"request": "launch",
"name": "Launch 6 Program",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}/6/entry.js"
}
]
}
utils/database.js:
import mysql from "mysql";
export const pool = mysql.createPool({
connectionLimit: 100,
host: "localhost",
user: "root",
password: "password",
database: "no_replicate",
});
entry.js:
"use strict";
import { pool } from "./utils/database.js";
pool.end(function (err) {
if (err) {
return console.log("error:" + err.message);
}
console.log("Close the database connection.");
});
pool.getConnection(function (err, connection) {
// execute query
// ...
console.log("SSSS");
});
Any help would make my day. Thanks
in utils/database.js:
const mysql = require("mysql");
const pool = mysql.createPool({
connectionLimit: 100,
host: "localhost",
user: "root",
password: "password",
database: "no_replicate",
});
module.exports = pool
in entry.js
const pool = require('./utils/database.js');
pool.end(function (err) {
if (err) {
return console.log("error:" + err.message);
}
console.log("Close the database connection.");
});
pool.getConnection(function (err, connection) {
// execute query
// ...
console.log("SSSS");
});
and in Nodejs we import like with require('package-name')

Message.Create is not a function sequelize cli

I have installed mysql sequelize in my project then I creadted Message Model using sequelize command which create model and migration file .I also given the db credentials in config.json file.Now I am trying to insert record in my db but getting this error here is my model file
DO i need to make db connection explicitly or it auto picks the
credential from config.json file to make connection ?
models/messages.js
'use strict';
module.exports = (sequelize, DataTypes) => {
var Messages = sequelize.define('Messages', {
room: DataTypes.STRING,
nickname: DataTypes.STRING,
message: DataTypes.STRING,
receiver: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
return Messages;
};
here is config.json file
config/config.json
{
"development": {
"username": "root",
"password": "asad",
"database": "chat",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
and here is my server file to save record
app.js file
var express = require('express');
var router = express.Router();
var app = express();
var server = require('http').createServer(app);
server.listen(4000);
var Messages=require('../models/Messages.js');
router.post('/', function(req, res, next) {
var a =req.body;
Messages.create(a).then(() => {
console.log('success ')
})
})
make sequelize connection instance and export it, please use config according to your environment
const sql = new Sequelize(config.database, config.username, config.password, {
host: config.host,
dialect: config.dialect,
pool: {
max: 5,
min: 0,
idle: 10000
},
});
module.export = sql;
In your app.js import sql instance and connect your db before starting your server.
var express = require('express');
var router = express.Router();
var app = express();
var server = require('http').createServer(app);
var sql = require(./sql);
sql.authenticate().then(()=>{
server.listen(4000);
});
var Messages= sql.import('../models/Messages.js');
router.post('/', function(req, res, next) {
var a =req.body;
Messages.create(a).then(() => {
console.log('success ')
})
})