How can I connect to mysql from nodejs? - mysql

I am working on a node JS project with mysql database. I have created a new file db.js that is used to connect to the database. My structure looks like below.
- server
- config
- db.js
- index.js
db.js
const mysql = require('mysql');
export default() =>{
const db = mysql.createConnection ({
host: 'localhost',
user: 'root',
password: '',
database: 'socha'
});
// connect to database
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to database');
});
}
index.js
const express = require('express');
const dbConfig = require('./config/db');
const app = express();
My problem is I cannot connect to the db.js file from index.js file.
Can anybody tell me what mistake I have been doing.
Thank You

You can change your index.js and db.js to this.
This should create the connection if DB credentials are correct
db.js
const mysql = require('mysql');
const connect = () => {
const db = mysql.createConnection ({
host: 'localhost',
user: 'root',
password: '',
database: 'socha'
});
// connect to database
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to database');
});
}
module.exports = {
connect
}
index.js
const express = require('express');
const dbConfig = require('./config/db');
const app = express();
// Connecting to db
dbConfig.connect();

Related

Unable to make api request to backend getting Axios network error

I was making one app with frontend react.js uses axios to api call and for backend i am using express and node with database mysql while making call to api url i am getting error for access denied error
Error: ER_ACCESS_DENIED_ERROR: Access denied for user ''#'localhost' (using password: NO)
If this is not the case i will be getting axios network error
Axios Network error
i dont know which port to use if i use 3306 port it is already in use. Please take a look at code and suggest about optimization and a better way...
thank you....
config.js will be saving confiq for the connection db
config.js
const config = {
db: {
host: "localhost",
user: "new_user",
password: "password",
database: "db",
},
};
module.exports = config;
db.js will create the connection
db.js
const mysql = require("mysql");
const config = require("./config");
var con = mysql.createPool(config);
module.exports = con;
this is where the express and app server is supposed to create
index.js
const express = require("express");
var mysql = require("mysql");
const cors = require("cors");
const app = express();
app.use(express());
app.use(cors());
const TablesRoutes = require("./routes/TablesRoutes");
//routes
app.use("/", TablesRoutes);
app.listen(8000, () => {
console.log("Running on port :8000");
});
api routes to call from frontend
routes
const express = require("express");
const {
postTableDes,
alterTable,
showTables,
} = require("../Controllers/Tables");
const tablerouter = express.Router();
tablerouter.get("/", showTables);
tablerouter.post("/", postTableDes);
module.exports= tablerouter;
where showing the table act
controller
const con = require("../Config/db");
//get tables
const showTables = async (req, res) => {
//try {
var sql = `show tables`;
const data = await con.query(sql, (err, res)=>{
if(err){
console.log(err);
res.status(404).json({ error: "No show table" });
return;
}
console.log(res);
res.status(202).json(data);
});
module.exports = showTables;
Try to change the config.js to (the createPool call does not expect an object with db property):
const config = {
host: "localhost",
user: "new_user",
password: "password",
database: "db",
};
module.exports = config;

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...

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.

PROTOCOL_CONNECTION_LOST Node-MySQL

I have made a simple node express server using my-sql. The server runs for few minutes but then crashes with the following message. I have tried to handle the error, but the app just throws the erro and then crashes. Please suggest the best way to handle these errors.
Code of my server:
import express from 'express'
import cors from 'cors';
import dotenv from 'dotenv';
import mysql from 'mysql';
const app = express();
app.use(cors());
app.use(express.json());
dotenv.config();
const connection = mysql.createConnection({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
port: process.env.MYSQL_PORT,
database: process.env.MYSQL_DATABASE
})
const DBNAME = process.env.DBNAME || 'students';
const PORT = process.env.PORT || 5000;
//GET ALL STUDENTS
app.get('/api/student', (req, res) => {
const sort = 'percentage DESC'
const getQuery = `SELECT * from ${DBNAME} ORDER BY ${sort}`;
connection.query(getQuery, (error, result) => {
if(error) {
throw error
} else {
res.json(result)
}
});
})
app.listen(PORT, () => {
console.log(`Running on port ${PORT}`)
})

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.