Home > Mobile >  Deploying Nodejs Express js App on heroku
Deploying Nodejs Express js App on heroku

Time:08-11

I'm trying to deploy my app on heroku, but I'm always getting this error

2022-08-11T12:49:12.131468 00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306
2022-08-11T12:49:12.131469 00:00 app[web.1]: at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
2022-08-11T12:49:12.131470 00:00 app[web.1]: errno: -111,
2022-08-11T12:49:12.131470 00:00 app[web.1]: code: 'ECONNREFUSED',
2022-08-11T12:49:12.131470 00:00 app[web.1]: syscall: 'connect',
2022-08-11T12:49:12.131471 00:00 app[web.1]: address: '127.0.0.1',
2022-08-11T12:49:12.131471 00:00 app[web.1]: port: 3306,
2022-08-11T12:49:12.131471 00:00 app[web.1]: fatal: true
2022-08-11T12:49:12.131472 00:00 app[web.1]: }
2022-08-11T12:49:12.131494 00:00 app[web.1]:
2022-08-11T12:49:12.131494 00:00 app[web.1]: Node.js v18.7.0

Could anybody help me solve this problem? This is the server.js

const express = require('express')
const app = express()

app.set('view engine', 'ejs')

const filterByDateRouter = require('./routes/filterByDate');
const filterByLogsRouter = require('./routes/filterByLogs');
const mainPageRouter = require('./routes/index'); 

app.use("/filterByDate", filterByDateRouter)
app.use("/filterByLogs", filterByLogsRouter)
app.use("/",mainPageRouter)
app.use(express.static(__dirname   '/public/css'))
app.use(express.static(__dirname   '/public/js'))


app.listen(process.env.PORT || 3000)

this is the database connection:

var connection = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  connectionLimit:10,
  database: process.env.DB_NAME,
});

I'm using clearMYSQL from heroku to deploy my database, and all the fields saved in the .env are right

CodePudding user response:

You can read the CLEARDB_DATABASE_URL and parse it:

const url = new URL(process.env.CLEARDB_DATABASE_URL);
const host = url.hostname;
const port = url.port || 3306;
const user = url.username;
const password = url.password;
const database = url.pathname.substring(1);
const connection = mysql.createPool({
  host,
  user,
  password,
  connectionLimit:10,
  database,
  port
});

CodePudding user response:

You are trying to connect to 127.0.0.1, while heroku doesn't host the database on the same container. Looking at the heroku-documentation, you will need to get the host from the config, by doing:

heroku config | grep CLEARDB_DATABASE_URL

This will return you a mysql://-url, which you should add as a variable. This is also described in the documentations and achievable by doing:

heroku config:set DATABASE_URL='<result-of-first-command>'

More information is available here.

CodePudding user response:

You can also add your enviroment variables that are provided by hosting providers. You can also add env variables in heroku from settings>Config Vars

https://i.stack.imgur.com/Qacht.png

  • Related