Стас Рябцев
Стас Рябцев

Reputation: 1408

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

enter image description here

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;
};

Upvotes: 0

Views: 643

Answers (1)

Ziyo
Ziyo

Reputation: 604

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

Upvotes: 1

Related Questions