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}`)
})
Related
const express = require('express')
const app = express()
// const mysql = require('mysql')
const mysql = require('./db')()
const cors = require('cors')
require('dotenv').config();
const port = process.env.PORT || 5000
app.use(express.json())
app.use(cors())
app.listen(port, () => console.log(`${port}`))
app.get('/', (req, res) => {
res.send("hi")
})
const connection = mysql.init()
mysql.open(connection)
This is my server.js code.
const mysql = require('mysql')
require('dotenv').config();
module.exports = function() {
return {
init: function () {
return mysql.createConnection({
host: process.env.HOST,
user: process.env.USER,
password: process.env.PASSWORD,
database: process.env.DATABASE,
port: process.env.PORT
})
},
open: function(con) {
con.connect(function(err) {
// if (err) throw err
// console.log('Connected!')
if(err) {
console.log('mysql connection error: '+err)
} else {
console.log('mysql is connected successfully.')
}
})
}
}
}
And this is my db.js code...
I expect the port number and message "mysql is connected successfully" to be printed when this code is executed. But when I run it, nothing is output except for the port number. Even an error message.
So I can't verify that the database connection was made properly. Why is the contents of the connect() function not executed?
You have used same environment variable for server port and database port. Please change variable name PORT of database port to DB_PORT in .env file. Then change the environment variable name in the database port of db.js file as well.
db.js
const mysql = require("mysql");
require("dotenv").config();
module.exports = function () {
return {
init: function () {
return mysql.createConnection({
host: process.env.HOST,
user: process.env.USER,
password: process.env.PASSWORD,
database: process.env.DATABASE,
port: process.env.DB_PORT,
});
},
open: function (con) {
con.connect(function (err) {
// if (err) throw err
// console.log('Connected!')
if (err) {
console.log("mysql connection error: " + err);
} else {
console.log("mysql is connected successfully.");
}
});
},
};
};
example .env file
PORT=8080
HOST=localhost
USER=root
PASSWORD=root
DATABASE=dbname
DB_PORT=3306
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.
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.
I'm trying to build an application with Node and Express, it worked well yesterday until today I got this error:
{
code: "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR",
fatal: false
}
Google says I should use createPool rather than createConnection, but I'm not sure how to do it in my case. Here is my code:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
const SELECT_ALL_USERS_QUERY = 'SELECT * FROM `mySchema`.`myTable`;';
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'abcdefg',
database: 'mySchema'
});
connection.connect(err => {
if (err) {
return err
}
});
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /mySchema to see contents')
});
app.get('/myTable', (req, res) => {
connection.query(SELECT_ALL_USERS_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
}
})
});
app.listen(4000, () => {
console.log('MySchema SQL server listening on PORT 4000');
});
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host: 'localhost',
user: 'root',
password: 'abcdefg',
database: 'mySchema'
});
// for an example.....
pool.getConnection(function(err, connection) {
if (err) throw err; // not connected!
app.get('/myTable', (req, res) => {
// Use the connection
connection.query('SELECT something FROM sometable', function (error, results, fields) {
// When done with the connection, release it.
connection.release();
// Handle error after the release.
if (error) throw error;
// Don't use the connection here, it has been returned to the pool.
});
});
});
If you would like to close the connection and remove it from the pool, use connection.destroy() instead. The pool will create a new connection the next time one is needed.
Connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. Connections are also cycled round-robin style, with connections being taken from the top of the pool and returning to the bottom.
When a previous connection is retrieved from the pool, a ping packet is sent to the server to check if the connection is still good.
you can follow this link: https://github.com/mysqljs/mysql#pooling-connections
To help other people, thought I'd post the complete solution which worked for me:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /mySchema to see contents')
});
const SELECT_ALL_USERS_QUERY = 'SELECT * FROM `mySchema`.`myTable`;';
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'abcdefg',
database: 'mySchema',
debug: false
});
pool.getConnection((err, connection) => {
if (err) throw err;
app.get('/myTable', (req, res) => {
connection.query(SELECT_ALL_USERS_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
};
});
console.log(connection);
});
});
app.listen(4000, () => {
console.log('MySchema SQL server listening on PORT 4000');
});
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();