admin管理员组文章数量:1122832
I need to deploy an inventory system on a subdomain, it is built in node.js and express.js and it was originally deployed on a physical server via PM2. I need to upload it to a web hosting in cpanel.
Before when I was running on a local environment, I used the livereload and nodemon packages, and then I uninstalled them when I moved to cpanel.
I also put the index.js outside the src folder, because cpanel gave me the Phusion Passenger error, then it no longer appears and now I get the 500 error. Now it manages to redirect me to the /signin
url which redirects to the login first.
500 internal server error:
The project structure:
>src
>uploads
index.js
package-lock.json
package.json
README.md
server.log
"src" is the folder that contains keys.js file with the mysql credentials, database.js that makes the connection to it, the routes, views, js libraries, public folders.
"uploads" is the folder that multer uses to upload files.
index.js:
// Importación de Módulos y Paquetes Necesarios
const express = require('express'); // Framework Backend de Node.js para crear Aplicaciones Web y APIs
const morgan = require('morgan'); // Middleware para ver en Consola las peticiones HTTP
const exphbs = require('express-handlebars'); // Sistema de Plantillas Handlebars para Express
const path = require('path'); // Modulo de Node.js para trabajar Rutas de Archivos y Directorios
const favicon = require('serve-favicon'); // Usar Favicon para la Pestaña
const bodyParser = require('body-parser'); // Libreria para Enviar Datos de Forms Dinamicos al Backend
const flash = require('express-flash'); // Middleware de Express para ver mensajes y errores en peticiones HTTP
const session = require('express-session') // Middleware de Express para Manejo de Sesiones en la Aplicación
const mysqlStore = require('express-mysql-session') // Middleware de Express para Manejo de Sesiones en MySQL
const { database, secretkey } = require('./src/keys.js'); // Obtención de Dato 'database' y 'secretKey' del archivo keys.js
const passport = require('passport'); // Autenticación para peticiones HTTP
// * Inicialización de la aplicación Express **********************************************************************************************
const app = express();
require('./src/lib/passport.js');
app.use(bodyParser.json()); // Configuracion del Body Parser
// * Configuración de la aplicación (Definición de Puerto, Directorio de Vistas y Directorio Public) ***************************************
app.set('port', process.env.PORT || 4500); // Cambiado Puerto a 4500 en Local
app.set('views', path.join(__dirname, './src/views'));
app.set('public', path.join(__dirname, './src/public'));
app.use(favicon(path.join(__dirname, './src/public', 'favicon.ico')))
// * Configuración del Motor de Plantillas Handlebars **************************************************************************************
app.engine('.hbs', exphbs({
defaultLayout: 'main', // Definición de Main como Layout Principal
layoutsDir: path.join(app.get('views'), 'layouts'), // Definición de Directorio de Layout
partialsDir: path.join(app.get('views'), 'partials'), // Definición de Directorio de Partials
extname: '.hbs', // Extensión de Archivo de Handlebars
helpers: require('./src/lib/handelbars.js') // Librería de Handlebars
}));
app.set('view engine', '.hbs'); // Definir Motor de Vista
// * Middlewares (funciones que se ejecutan antes de llegar a las rutas) *******************************************************************
// Configuración de la sesión
app.use(session({
secret: secretkey,
// cookie:{maxAge: 60000},
resave: true,
saveUninitialized: false,
store: new mysqlStore(database)
}));
// Parseo de datos JSON y URL-encoded
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// Middleware de desarrollo para mostrar logs en la consola
app.use(morgan('dev'));
// Mensajes Flash
app.use(flash());
// Inicialización de Passport y configuración de sesión de usuario en Este Orden
app.use(passport.initialize());
app.use(passport.session());
// Variables Globales Accesibles en todas las Vistas
app.use((req, res, next) => {
app.locals.user = req.user;
app.locals.messages = req.flash('messages');
next();
});
// Carga de Rutas
app.use(require('./src/routes/index.js'));
app.use(require('./src/routes/home.js'));
app.use(require('./src/routes/authentication.js'));
app.use('/functions', require('./src/routes/functions.js'));
app.use('/persons', require('./src/routes/persons.js'));
app.use('/types', require('./src/routes/types.js'));
app.use('/products', require('./src/routes/products.js'));
app.use('/roles', require('./src/routes/roles.js'));
app.use('/bodegas', require('./src/routes/bodegas.js'));
app.use('/textos', require('./src/routes/textos.js'));
app.use('/ingresos', require('./src/routes/ingresos.js'));
app.use('/produccion', require('./src/routes/produccion.js'));
app.use('/envasado', require('./src/routes/envasado.js'));
app.use('/despacho', require('./src/routes/despacho.js'));
app.use('/transferencia', require('./src/routes/transferencia.js'));
app.use('/import', require('./src/routes/import.js')); // Nueva Ruta para Importar Archivos
// Carpeta de archivos estáticos (CSS, imágenes, etc.)
app.use(express.static(path.join(__dirname, './src/public')));
// Inicio del servidor
app.listen(app.get('port'), () => {
console.log('Server on port ', app.get('port'));
});
package.json:
{
"name": "controlstock",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "node index.js",
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"bootstrap-icons": "^1.6.1",
"connect-flash": "^0.1.1",
"cookie-parser": "^1.4.6",
"express": "^4.18.1",
"express-flash": "0.0.2",
"express-handlebars": "^5.3.4",
"express-mysql-session": "^2.1.7",
"express-session": "^1.17.2",
"express-validator": "^6.13.0",
"html-pdf": "^3.0.1",
"jquery-ui": "^1.13.3",
"morgan": "^1.10.0",
"multer": "^1.4.5-lts.1",
"mysql": "^2.18.1",
"passport": "^0.5.0",
"passport-local": "^1.0.0",
"pdf-constructor": "^1.0.0",
"pdfkit": "^0.13.0",
"pdfkit-table": "^0.1.99",
"serve-favicon": "^2.5.0",
"timeago.js": "^4.0.2",
"xlsx": "^0.18.3"
}
}
database.js:
// Importación de módulos y paquetes necesarios
const mysql = require('mysql');
const {database} = require('./keys');
const {promisify} = require('util');
// Crear Pool de Conexión a BD
const dbPool = mysql.createPool(database);
// Manejo de Errores en el Pool de Conexión a BD
dbPool.getConnection((err, connection) => {
if(err){
if (err.code === 'PROTOCOL_CONNECTION_LOST'){
console.error('DATABASE CONNECTION WAS CLOSED')
}
if (err.code === 'ER_CON_COUNT_ERROR'){
console.error('DATABASE HAS TO MANY CONNECTIONS')
}
if (err.code === 'ECONREFUSED'){
console.error('DATABASE CONNECTION WAS REFUSED')
}
}
// Mensaje de Conexión a BD Exitosa
if(connection) connection.release();
console.log('DATABASE is CONNECTED');
return;
});
// Promisify Query (Convierte de Callbacks a Promesas para ocupar Async Await)
dbPool.query = promisify(dbPool.query);
module.exports = dbPool ;
This is the app information uploaded to cpanel with "Setup node.js App":
My passenger.log (Only appears that console.log of the correct connection to mysql and a get request from morgan):
.htaccess:
本文标签: Deploying NodejsExpressjs in Cpanel throws Error 500 Internal Server ErrorStack Overflow
版权声明:本文标题:Deploying Node.jsExpress.js in Cpanel throws Error 500 Internal Server Error - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736301912a1931342.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论