我为一个项目开发了一个REST API,我试图将它上传到Heroku。在我启动应用程序的那一刻,它运行了几分钟,然后崩溃了。
任何帮助都是有用的,提前感谢。🙏
一些数据、表格和变量,我用西班牙语,对不起。:/
- node_modules
- 请求(一些http请求测试)
- .gitignore
- app.js
- package-lock.json
- package.json
输入图片描述
这是唯一的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可以正常工作几分钟,然后停止工作。
- Api工作正常
输入图片描述
<<ul>Api下来/gh>输入图片描述
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 restart
, API再次工作,但有相同的问题。
感谢您的宝贵时间🙏
我怀疑是连接超时了。这里的最佳实践是为每个查询创建一个新连接,然后关闭它,而不是只有一个连接。