Error: Connection lost: The server closed the connection. mysql node - javascript

I have seen many solutions to this problem in google, but I could not apply them. API works well, but after some time this error appears.
...................................................................................................................................................................................................................................................................
index.js
const express = require('express');
const app = express();
const router = express.Router();
const path = require('path');
const habalka = require('./routes/habalka')(router);
const port = process.env.PORT || 3000;
app.use('/api/habalka', habalka);
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
db.js
const mysql = require('mysql');
const db_config = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'habalka'
});
db_config.connect(function(err) {
if (err) {
console.log('error when connecting to db:', err);
}
});
module.exports = db_config;
habalka.js
const connect = require('../db');
module.exports = (router) => {
router.get('/get', (req, res) => {
let sql = 'SELECT * FROM test';
connect.query(sql, (err, results) => {
if (err) throw err;
res.json(results);
});
});
return router;
};

I would suggest using Sequelize ORM. It abstracts away writing raw SQL and it is much safer.

Related

How can I notify that I successfully created a sql pool in express js?

I'm creating a restful API using mysql and expressjs, here's an example of how I send requests to my database:
server.js:
const express = require('express'),
bodyParser = require('body-parser'),
PORT = 8080,
app = express();
//setting up routes
const userRoute = require('./routes/user.route');
//parsebody of req into json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use('/user', userRoute);
app.listen(
PORT,
() => console.log(`API fired up on http://localhost:${PORT}`)
)
userRoute:
const express = require('express');
const userRoute = express.Router();
const User = require('../controllers/user.controllers');
// Retrieve all Users
userRoute.route('/users').get(((req, res) => {
User.findAll(req,res);
}));
userController:
const User = require("../models/user.model.js");
// Retrieve all Customers from the database.
exports.findAll = (req, res) => {
User.getAll((err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while retrieving user."
});
else res.send(data);
});
}
userModel:
const sql = require('../tools/db');
User.getAll = result => {
sql.query("SELECT * FROM Utilisateur", (err, res) => {
if (err) {
console.log("erreur: ", err);
result(null, err);
return;
}
console.log("Utilisateurs: ", res);
result(null, res);
});
};
db:
const mysql = require('mysql');
const dbConfig = require("../config/database.config");
// Create a connection to the database
const connection = mysql.createPool({
host: dbConfig.HOST,
user: dbConfig.USER,
password: dbConfig.PASSWORD,
database: dbConfig.DB,
port: dbConfig.PORT
}) || null;
/*if(connection) console.log("Connected to "+ connection.config.database +" database!")*/
module.exports = connection;
My request works perfectly but I'm trying to console log the fact that my API successfuly connected to my database, (I commented my attempt) but the log gives me a:
Connected to undefined database!
is there a best way to log my connection success (and maybe handle if there's any error in the process) ? if not how can I make connection.config.database correctly write my database name
The issue is you're calling an undefined property in the connection object.
This should work just fine:
const mysql = require("mysql");
const connection = mysql.createPool({
host: dbConfig.HOST,
user: dbConfig.USER,
password: dbConfig.PASSWORD,
database: dbConfig.DB,
port: dbConfig.PORT
});
const database = connection.config.connectionConfig.database;
console.log(`Connected to ${database} database!`);
You have to make sure the mysql.createPool function has finished executing before calling console.log.
Try this change:
const connection = mysql.createPool({
host: dbConfig.HOST,
user: dbConfig.USER,
password: dbConfig.PASSWORD,
database: dbConfig.DB,
port: dbConfig.PORT
}).then(con => {
console.log(con.config.databse)
return con
})

Getting a 502 Bad Gateway error when I try and require code from Node.js files

I am looking to start including my route files in my Node.js and express application. However, when I require the local route files into my server.js file, and try to run that on Nginx, I get a 502 Bad Gateway error.
The code that is giving me trouble is currently commented out. Any ideas on what might be causing this performance?
server.js
require('dotenv').config();
const express = require('express');
const bodyparser = require('body-parser');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
// const oidc = require('./okta');
// const searchRouter = require('./routes/search');
// const inputRouter = require('./routes/input');
// const dataRouter = require('./routes/view-all');
const app = express();
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.sendFile(__dirname + '/views/index.html');
});
app.get('/page', function(req, res) {
res.render(__dirname + '/views/optishop.ejs');
});
const listener = app.listen(8080, function() {
console.log('Your app is listening on port ' + listener.address().port);
});
Edit: This is the file being required in the searchRouter declaration.
search.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const oidc = require('../okta');
const router = express.Router();
router.post('/search', oidc.ensureAuthenticated(), async (req, res) => {
await MongoClient.connect(
process.env.MONGODB_URI,
{ useUnifiedTopology: true },
async (err, client) => {
assert.equal(null, err);
const db = client.db('test');
const arr = req.body.item.trim().split(/; */gi);
const user = req.session.passport.user.userinfo.sub;
const cursor = await db
.collection('test')
.find({
user
})
.toArray();
const filteredCursor = cursor.filter(obj => {
return arr.includes(obj.item);
});
res.render('index', {
cursor: filteredCursor
});
// res.send(filteredCursor);
client.close();
}
);
});
module.exports = router;

Why does my http request not return a response

I have several routes in my api that work perfectly but while trying to implement a comment system I dont receive any response either from going to the url (node backend) or from postman.
My server JS is as follows and works for post, teams, users, but it does not work for comments.
Server.js File Below:
//load server
const express = require('express');
var cors = require('cors');
const app = express();
const morgan = require('morgan');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const multer = require('multer');
//db
const db = require('./config/db');
db
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
//image upload
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public')
},
filename: function (req, file, cb) {
let date = new Date(Date.now());
cb(null, date.getDay() + '-' + date.getDate() + '-' + file.originalname )
}
})
var upload = multer({ storage: storage }).single('file')
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))
app.use(cors());
app.use(express.static('./public'))
app.use(morgan('combined'));
const router = require('./routes/user.js')
const postRoute = require('./routes/post.js');
app.use('/posts', require('./routes/post.js'));
app.use('/teams', require('./routes/teams.js'));
app.use('/comments', require('./routes/comments.js'));
app.use(router)
app.listen(port, () => console.log(`Listening on port ${port}`));
Below are my comment api routes:
const express =require('express');
const mysql = require('mysql');
const db = require('../config/db');
const Comments = require('../models/Comments');
// const connection = getConnection()
const router = express.Router();
const Sequelize = require('sequelize');
router.get('/', (req, res) =>
Comments.findAll().then( comments => {
console.log(comments);
res.json(comments);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
router.get('/:id', (req, res) =>
Comments.findAll({
where: {
postId: req.params.id
}
}).then( comments => {
console.log(comments);
res.json(comments);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
router.post('/add/:id', (req, res) => {
Comments.create(req.body).then(comments => {
console.log(req.body)
res.json(comments);
console.log(comments)
})
.catch(err => console.log(err))
});
module.exports = router;
Im posting my Teams Api Route To Show what i have that has been working perfectly for me:
//will contain all user routes
const express =require('express');
const mysql = require('mysql');
const db = require('../config/db');
const Teams = require('../models/Teams');
// const connection = getConnection()
const router = express.Router()
const Sequelize = require('sequelize');
//find all teams
router.get('/', (req, res) =>
Teams.findAll().then( team => {
console.log(team);
res.json(team);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
//find Team by ID
router.get('/:id', (req, res) =>
Teams.findAll({
where: {
id: req.params.id
}
}).then( team => {
console.log(team);
res.json(team);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
//add users image
module.exports = router;
It was because It was expecting a request, and i wasnt giving it one. Have to just return response.
router.get('/').then(res => {
Comments.findAll().then(comments => {
console.log(comments);
res.json(comments.data);
})
})

I cant PUT or DELETE anything on my MySQL DB with NodeJs

I cant put and delete anything on my database, and i think that my core are correct
This is for a project, running MariaDB 10.1.37, Apache 2.
The code:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const port = 3000;
const mysql = require('mysql');
function execSQLQuery(sqlQry, res){
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: '',
database: 'usdb'
});
connection.query(sqlQry, function(error, results, fields){
if(error)
res.json(error);
else
res.json(results);
connection.end();
console.log('executou!')
})
}
//cofigurando body parser para pegar os POSTS mais tarde
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//definindo as rotas
const router = express.Router();
router.get('/',(req,res) => res.json({message: 'Funcionando!'}));
app.use('/',router);
router.get('/substances',(req, res) =>{
execSQLQuery('SELECT * FROM organicssubstances', res);
});
router.get('/substance/:id?', (req, res) =>{
let filter = '';
if(req.params.id) filter = ' WHERE id=' + parseInt(req.params.id);
execSQLQuery("SELECT * FROM organicssubstances"+filter, res);
});
router.get('/substance/:id', (req,res) =>{
execSQLQuery("DELETE FROM organicssubstances WHERE id=" + parseInt(req.params.id), res);
});
router.get('/substances', (req,res) =>{
const substance = req.body.substring(0,150);
const formula = req.body.substring(0,150);
execSQLQuery(`INSERT INTO organicssubstances(substance, formula) VALUES('${substance}','${formula}')`, res);
});
//inicia o servidor
app.listen(port)
console.log('API Funcionando!')
Code of PUT and DELETE:
router.get('/substance/:id', (req,res) =>{
execSQLQuery("DELETE FROM organicssubstances WHERE id=" + parseInt(req.params.id), res);
});
router.get('/substances', (req,res) =>{
const substance = req.body.substring(0,150);
const formula = req.body.substring(0,150);
execSQLQuery(`INSERT INTO organicssubstances(substance, formula) VALUES('${substance}','${formula}')`, res);
});
I see this code on a site and just adapted to my use, but not working.
https://i.imgur.com/cDyyio4.png
https://i.imgur.com/y5zruZG.png
From what I have seen, you should define the route as put and delete. Not get
router.get(‘/urlforget’, callbackfunction);
router.put(‘/urlforput’, callbackfunction);

Other endpoints are ignored when using express.static

This is my index.js file:
const express = require('express');
const mongoose = require('mongoose');
const Post = require('./models/Post');
const keys = require('./config/keys');
const path = require('path');
mongoose.connect(keys.mongoURI);
const app = express();
app.use(express.static(path.join(__dirname, '../react-app/build')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../react-app/build',
'index.html'));
});
app.get('/posts', (req, res) => {
Post.find({}, (err, posts) => {
if(err) {
console.log(err);
res.sendStatus(500);
} else {
res.send(posts)
}
})
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`App listening on port ${PORT}`));
I've builded my react frontend to the location specified in the path.join. However, if I use the app.use(express.static(...)), if I use any path at all, it will always return index.html from my build.
I'd like to see the posts object when I got to '/posts' endpoint, but it doesn't work and I can't get the build serving working without express static.
EDIT:
I tried console logging inside '/' handler, but it logged nothing either. I got everything working when I remove the app.use line entirely. Some tutorials use this approach, why is not working?
So try this:
const express = require('express');
const mongoose = require('mongoose');
const Post = require('./models/Post');
const keys = require('./config/keys');
const path = require('path');
mongoose.connect(keys.mongoURI);
const app = express();
app.use(express.static(path.join(__dirname, '../react-app/build')));
app.get('/posts', (req, res) => {
Post.find({}, (err, posts) => {
if(err) {
console.log(err);
res.sendStatus(500);
} else {
res.send(posts)
}
})
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../react-app/build',
'index.html'));
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`App listening on port ${PORT}`));

Categories