javascript - 错误: Connection lost: The server closed the connection. mysql Node

标签 javascript mysql node.js rest api

enter image description here

我在google上看到了很多这个问题的解决方案,但我无法应用它们。 API 运行良好,但一段时间后会出现此错误。

...................................................... ...................................................... ...................................................... ...................................................... ...................................................... …………

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;

哈巴尔卡.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;
};

最佳答案

我建议使用 Sequelize ORM。它抽象了原始 SQL 的编写,并且更加安全。

关于javascript - 错误: Connection lost: The server closed the connection. mysql Node ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52797954/

相关文章:

mysql - 错误代码 : 1062. key '1' 的重复条目 'PRIMARY'

javascript - 制作浏览器和 Node 兼容的 Javascript 库

javascript - 包装一个节点值

javascript - 网站可以强制浏览器进入全屏模式吗?

php - 查询在 phpmyadmin 中有效,但在 PHP 中无效

python - Flask-MySQLdb 自动提交?

javascript - 函数错误: Uncaught TypeError: undefined is not a function

javascript - 下拉菜单不会在第二次单击时关闭

node.js - 如何解析 Angular for Vimeo SDK 所需的 'fs' 模块

javascript - 算法 : finding nearby value the fastest way