首页 > 解决方案 > 为什么 Heroku 服务器在几分钟后关闭?

问题描述

我为一个项目开发了一个 REST API,并尝试将其上传到Heroku。在我启动应用程序的那一刻,它会运行几分钟并崩溃。

任何帮助都是有用的,在此先感谢。

我使用的一些数据、表格和变量是西班牙语,抱歉。:/

结构体

在此处输入图像描述

编码

这是我在项目中使用的唯一 JavaScript 文件。PS:为了安全起见,我更改了连接信息

const express = require('express');
const mysql = require('mysql');
const bcrypt = require('bcrypt');

const bodyParser = require('body-parser');

const PORT = process.env.PORT || 3050;

const app = express();
app.use(express.json());

//MySql
var cnx = mysql.createConnection({
    host: 'any_host',
    user: 'any_user',
    password: 'any_password',
    database: 'any_database'
});

//rutas
app.get('/', (req, res) => {
    res.send('Bienvenido a mi API');
});

app.get('/usuarios', (req, res) => {
    const sql = 'SELECT * FROM usuario';
    cnx.query(sql, (error, results) => {
        if (error) throw error;

        if(results.length > 0){
            res.json(results);
        }else{
            res.send('No hay resultados')
        }
    });
});

app.get('/usuarios/:id', (req, res) => {

    const { id } = req.params;
    const sql = `SELECT * FROM usuario WHERE idusuario = ${id}`;

    cnx.query(sql, (error, result) => {
        if (error) throw error;

        if (resul.length > 0) {
            res.json(result);
        }else{
            res.send('No hay resultados');
        }
    });
});

app.post('/add', (req, res) => {
    const sql = 'INSERT INTO usuario SET ?';

    const saltRounds = 10;
    const contraseñaHash = bcrypt.hash(req.body.contraseña, saltRounds);
    const usuarioObj = {
        cuenta: req.body.cuenta,
        contraseña: contraseñaHash,
        nombre: req.body.nombre,
        apellido: req.body.apellido
    };

    cnx.query(sql, usuarioObj, error => {
        if (error) throw error;
        res.send('Usuario creado');
    });
});

app.put('/update/:id', (req, res) => {
    const { id } = req.params;
    const { cuenta, contraseña, nombre, apellido } = req.body;
    var sql = mysql.format(
        'UPDATE usuario SET cuenta = ?, contraseña = ?, nombre = ?, apellido = ? WHERE idusuario = ?',
        [cuenta, contraseña, nombre, apellido, id]
    );

    cnx.query(sql, error => {
        if(error) throw error;
        res.send('Usuario actualizado!');
    });
});

app.delete('/delete/:id', (req, res) => {
    const { id } = req.params;
    var sql = `DELETE FROM usuario WHERE idusuario = ${id}`;

    cnx.query(sql, error =>{
        if(error) throw error;
        res.send('Usuario eliminado!');
    });
});

// Check connect
cnx.connect(error => {
    if (error) throw error;
    console.log('Corriendo base de datos');
});

app.listen(PORT, () => console.log(`El servidor esta corriendo en el puerto ${PORT}`));

这是package.json

{
  "name": "api_madison",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "2.0.12"
  },
  "dependencies": {
    "bcrypt": "5.0.1",
    "body-parser": "1.19.0",
    "mysql": "2.18.1",
    "express": "4.17.1"
  }
}

这是.gitignore

/node_modules/

HEROKU

API 可以正常工作几分钟,然后停止工作。

在此处输入图像描述

在此处输入图像描述

CLI HEROKU

当我启动命令heroku logs --tail时,这会出现

在此处输入图像描述

2021-10-05T06:03:15.581449+00:00 heroku[router]: at=info method=GET path="/usuarios" host=apimadison.herokuapp.com request_id=6deca321-588c-411d-b81a-e231eacb6eaf fwd="190.42.207.86" dyno=web.1 connect=0ms service=38ms status=200 bytes=2352 protocol=https
2021-10-05T06:04:15.512510+00:00 app[web.1]: events.js:377
2021-10-05T06:04:15.512519+00:00 app[web.1]: throw er; // Unhandled 'error' event
2021-10-05T06:04:15.512519+00:00 app[web.1]: ^
2021-10-05T06:04:15.512520+00:00 app[web.1]:
2021-10-05T06:04:15.512521+00:00 app[web.1]: Error: Connection lost: The server closed the connection.
2021-10-05T06:04:15.512521+00:00 app[web.1]: at Protocol.end (/app/node_modules/mysql/lib/protocol/Protocol.js:112:13)
2021-10-05T06:04:15.512522+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/mysql/lib/Connection.js:94:28)
2021-10-05T06:04:15.512522+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/mysql/lib/Connection.js:526:10)
2021-10-05T06:04:15.512522+00:00 app[web.1]: at Socket.emit (events.js:412:35)
2021-10-05T06:04:15.512522+00:00 app[web.1]: at endReadableNT (internal/streams/readable.js:1334:12)
2021-10-05T06:04:15.512523+00:00 app[web.1]: at processTicksAndRejections (internal/process/task_queues.js:82:21)
2021-10-05T06:04:15.512524+00:00 app[web.1]: Emitted 'error' event on Connection instance at:
2021-10-05T06:04:15.512526+00:00 app[web.1]: at Connection._handleProtocolError (/app/node_modules/mysql/lib/Connection.js:423:8)
2021-10-05T06:04:15.512527+00:00 app[web.1]: at Protocol.emit (events.js:400:28)
2021-10-05T06:04:15.512527+00:00 app[web.1]: at Protocol._delegateError (/app/node_modules/mysql/lib/protocol/Protocol.js:398:10)
2021-10-05T06:04:15.512527+00:00 app[web.1]: at Protocol.end (/app/node_modules/mysql/lib/protocol/Protocol.js:116:8)
2021-10-05T06:04:15.512528+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/mysql/lib/Connection.js:94:28)
2021-10-05T06:04:15.512528+00:00 app[web.1]: [... lines matching original stack trace ...]
2021-10-05T06:04:15.512529+00:00 app[web.1]: at processTicksAndRejections (internal/process/task_queues.js:82:21) {
2021-10-05T06:04:15.512529+00:00 app[web.1]: fatal: true,
2021-10-05T06:04:15.512529+00:00 app[web.1]: code: 'PROTOCOL_CONNECTION_LOST'
2021-10-05T06:04:15.512529+00:00 app[web.1]: }
2021-10-05T06:04:15.525602+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2021-10-05T06:04:15.525824+00:00 app[web.1]: npm ERR! errno 1
2021-10-05T06:04:15.530954+00:00 app[web.1]: npm ERR! api_madison@1.0.0 start: `node .`
2021-10-05T06:04:15.531050+00:00 app[web.1]: npm ERR! Exit status 1
2021-10-05T06:04:15.531156+00:00 app[web.1]: npm ERR!
2021-10-05T06:04:15.531244+00:00 app[web.1]: npm ERR! Failed at the api_madison@1.0.0 start script.
2021-10-05T06:04:15.531322+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2021-10-05T06:04:15.540307+00:00 app[web.1]:
2021-10-05T06:04:15.542432+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2021-10-05T06:04:15.542504+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2021-10-05T06_04_15_531Z-debug.log
2021-10-05T06:04:15.709436+00:00 heroku[web.1]: Process exited with status 1
2021-10-05T06:04:15.760747+00:00 heroku[web.1]: State changed from up to crashed
2021-10-05T06:07:24.606771+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/usuarios" host=apimadison.herokuapp.com request_id=231283ff-9748-4690-bd38-9f6e358673fe fwd="190.42.207.86" dyno= connect= service= status=503 bytes= protocol=https

顺便说一句,heroku restartAPI 再次工作,但有同样的问题。

感谢您的时间

标签: javascriptmysqlnode.jsrestheroku

解决方案


我的怀疑是连接超时。这里的最佳实践是为每个查询创建一个新连接并在之后关闭它,而不是只有一个连接。


推荐阅读