Deploy node.js express backend to heroku - node.js

Its my first time deploying on heroku and i keep getting errors, the build is succeeding but when the build finishes and i try to view the API response in the browser via heroku i get back an error of - Failed to load resource: the server responded with a status of 500 (Internal Server Error)
logs from heroku -
2021-12-11T19:16:54.702260+00:00 app[web.1]: npm ERR! errno 1
2021-12-11T19:16:54.708322+00:00 app[web.1]: npm ERR! example-create-react-app-express#1.0.0 start: node server.js
2021-12-11T19:16:54.708419+00:00 app[web.1]: npm ERR! Exit status 1
2021-12-11T19:16:54.708524+00:00 app[web.1]: npm ERR!
2021-12-11T19:16:54.708602+00:00 app[web.1]: npm ERR! Failed at the example-create-react-app-express#1.0.0 start script.
2021-12-11T19:16:54.708721+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2021-12-11T19:16:54.718471+00:00 app[web.1]:
2021-12-11T19:16:54.719294+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2021-12-11T19:16:54.719298+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2021-12-11T19_16_54_709Z-debug.log
2021-12-11T19:16:54.908600+00:00 heroku[web.1]: Process exited with status 1
2021-12-11T19:16:55.067169+00:00 heroku[web.1]: State changed from starting to crashed
2021-12-11T19:16:56.373561+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/api/hello" host=agile-spire-07157.herokuapp.com request_id=ab0c71fb-1be1-4829-b123-e57cc4e7fafd fwd="67.177.196.118" dyno= connect= service= status=503 bytes= protocol=https
2021-12-11T19:17:56.820732+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=agile-spire-07157.herokuapp.com request_id=b9615ee7-190d-44ce-8d97-c099d26149ca fwd="67.177.196.118" dyno= connect= service= status=503 bytes= protocol=https
Any help at all is greatly appreciated
Folder structure:
server.js:
const express = require('express');
const axios = require('axios');
require('dotenv').config();
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'));
});
const port = process.env.PORT || 2000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const apiKey = process.env.APIKEY
app.get('/api/hello', (req, res) => {
const { term, location } = req.query
const config = {
method: 'get',
url: `https://api.yelp.com/v3/businesses/search?term=${term}&location=${location}`,
headers: {
'Authorization': `Bearer ${apiKey}`
}
};
axios(config)
.then(function (response) {
return JSON.stringify(response.data, null, 2)
})
.then(function (jsonResponse) {
res.send(jsonResponse)
})
.catch(function (error) {
console.log(error);
});
});
app.listen(port, () => console.log(`Listening on port ${port}`))
package.json for server:
{
"name": "example-create-react-app-express",
"version": "1.0.0",
"scripts": {
"start": "node server.js",
"client": "cd ../client && yarn start",
"server": "nodemon server.js",
"dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
},
"engines": {
"node": "14.17.3"
},
"dependencies": {
"axios": "^0.24.0",
"body-parser": "^1.18.3",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1"
},
"devDependencies": {
"concurrently": "^4.0.1"
}
}

So i think i figured it out, it seems to be working and heres what i changed:
I added a Procfile in the root directory (make sure its a capital P) and added this to it -> web: node server.js
(so just put web: node(whatever your server file is named)
If you are storing your API key in a .env file then you have to let heroku know youre doing just that. You can let heroku know this by typing this command in terminal while in server folder
heroku config:set <key=value> If you did this right youll get back a response from heroku saying just that. This is a link i followed instructions with that worked for me https://dzone.com/articles/deploy-your-node-express-app-on-heroku-in-8-easy-s
Final server.js
const express = require('express');
const axios = require('axios');
require('dotenv').config();
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
const port = process.env.PORT || 2000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const apiKey = process.env.APIKEY
app.get('/api/hello', (req, res) => {
const { term, location } = req.query
const config = {
method: 'get',
url: `https://api.yelp.com/v3/businesses/search?term=${term}&location=${location}`,
headers: {
'Authorization': `Bearer ${apiKey}`
}
};
axios(config)
.then(function (response) {
return JSON.stringify(response.data, null, 2)
})
.then(function (jsonResponse) {
res.send(jsonResponse)
})
.catch(function (error) {
console.log(error);
});
});
app.listen(process.env.PORT || 2000, () => console.log(`Listening on port ${port}`))
Package.json for server:
{
"name": "example-create-react-app-express",
"version": "1.0.0",
"engines": {
"node": "14.17.3"
},
"scripts": {
"start": "node server.js",
"client": "cd ../client && yarn start",
"server": "nodemon server.js",
"dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
},
"dependencies": {
"axios": "^0.24.0",
"body-parser": "^1.18.3",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1"
},
"devDependencies": {
"concurrently": "^4.0.1"
}
}

Related

Everything works on Heroku local but have 503 error on Heroku live

This is my first time using Heroku to deploy app and I had done a lot of research, I had tried all the ways that seem to make it work but still no luck. Of course, everything works on development mode (localhost), so I try to deploy it. I successfully get everything to work on Heroku local, then I try to publish to Heroku live, but it gives me "Failed to load resource: the server responded with a status of 503 (Service Unavailable)" error. But people say the Heroku local is like if you have deployed the app online, you see what you will see after you have deployed it. I really don't know what's wrong
One thing I am not sure about is, whether my folder structure is too complicated.
This
is my folder structure, the root folder with package-lock.json, package.json, Procfile, and a sub-folder containing the frontend and backend folder.
But it is working on Heroku local, so even the folder structure is a bit complicated, but it is still pointing to the right location to function???
Profile:
web: npm start
Package.json in root folder:
"name": "comic-bookstore",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "cd comic-book-store/backend/ && node server.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false cd comic-book-store/frontend/ && npm install && npm run build",
"backend": "cd comic-book-store/backend/ && nodemon server.js",
"frontend": "cd comic-book-store/frontend/ && npm start",
"test": "echo \"Error: no test specified\" && exit 1"
}
Package.json in frontend folder:
"name": "frontend",
"version": "0.1.0",
"private": true,
"proxy": "https://localhost:3001",
"dependencies": {
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^11.2.7",
"#testing-library/user-event": "^12.8.3",
"axios": "^0.21.1",
"bootstrap": "^5.1.0",
"env-cmd": "^10.1.0",
"jwt-decode": "^3.1.2",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-router-dom": "^5.3.0",
"react-router-redux": "^5.0.0-alpha.9",
"react-scripts": "4.0.3",
"serve": "^13.0.2",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
Package.json in backend folder:
"name": "backend",
"version": "1.0.0",
"engines": {
"node": "16.15.0",
"npm": "8.5.5"
},
"description": "",
"main": "server.js",
"homepage": ".",
"dependencies": {
"bcrypt": "^5.0.1",
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"express-session": "^1.17.2",
"express-validator": "^6.12.1",
"jsonwebtoken": "^8.5.1",
"mongodb": "^4.1.0",
"mongoose": "^5.13.7",
"multer": "^1.4.3",
"nodemon": "^2.0.13",
"webpack": "^5.72.1"
},
"devDependencies": {
"#babel/core": "^7.15.0",
"#babel/node": "^7.x",
"#babel/plugin-proposal-class-properties": "^7.14.5",
"#babel/preset-env": "^7.15.0",
"#babel/preset-react": "^7.14.5",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.2",
"eslint": "^7.32.0",
"eslint-config-airbnb-base": "^14.2.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.24.0",
"eslint-plugin-prettier": "^3.4.0",
"eslint-plugin-react": "^7.24.0",
"prettier": "^2.3.2"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
}
server.js:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
// const session = require('express-session');
const cookieParser = require('cookie-parser');
const memberRoute = require('./routes/memberRoute');
const bookRoute = require('./routes/bookRoute');
const bookReservedRoute = require('./routes/bookReservedRoute');
const app = express();
const port = process.env.PORT || 3001;
const host = '0.0.0.0';
dotenv.config();
mongoose.connect(
process.env.DATABASE_ACCESS,
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
() => console.log('Database connected')
);
app.use(express.json());
app.use(cors());
app.use('/app', memberRoute);
app.use('/app', bookRoute);
app.use('/app', bookReservedRoute);
app.use('/uploads', express.static('uploads'));
if(process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, '../frontend/build')));
app.get('/^((?!(app)).)*$/', (req, res) => {
res.sendFile(path.join(__dirname, '../frontend', 'build', 'index.html'))
})
}
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.listen(port, host, () => {
console.log(`Express server listening on port ${port} and host ${host}!`);
});
env file in backend folder:
DATABASE_ACCESS = mongodb+srv://<my-database-credential>#comic-bookstore.4zots.mongodb.net/Member?retryWrites=true&w=majority
JWT_SECRET = HJ2H2WUHJ2CHghwhh3hjndsndhje3ujjwquyhnshwy22
NODE_ENV = production
I had copied the above config var to Heroku dashboard as well.
heroku logs --tail
2022-05-31T07:27:37.302703+00:00 heroku[web.1]: Process exited with status 1
2022-05-31T07:27:37.397210+00:00 heroku[web.1]: State changed from starting to crashed
2022-05-31T07:27:37.427713+00:00 heroku[web.1]: State changed from crashed to starting
2022-05-31T07:27:45.314929+00:00 heroku[web.1]: Starting process with command `npm start`
2022-05-31T07:27:46.948920+00:00 app[web.1]:
2022-05-31T07:27:46.948931+00:00 app[web.1]: > comic-bookstore#1.0.0 start
2022-05-31T07:27:46.948932+00:00 app[web.1]: > cd comic-book-store/backend/ && node server.js
2022-05-31T07:27:46.948932+00:00 app[web.1]:
2022-05-31T07:27:47.337366+00:00 app[web.1]: node:internal/modules/cjs/loader:1189
2022-05-31T07:27:47.337376+00:00 app[web.1]: return process.dlopen(module, path.toNamespacedPath(filename));
2022-05-31T07:27:47.337376+00:00 app[web.1]: ^
2022-05-31T07:27:47.337377+00:00 app[web.1]:
2022-05-31T07:27:47.337378+00:00 app[web.1]: Error: /app/comic-book-store/backend/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
2022-05-31T07:27:47.337378+00:00 app[web.1]: at Object.Module._extensions..node (node:internal/modules/cjs/loader:1189:18)
2022-05-31T07:27:47.337379+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-05-31T07:27:47.337379+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-05-31T07:27:47.337379+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-05-31T07:27:47.337380+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-05-31T07:27:47.337380+00:00 app[web.1]: at Object.<anonymous> (/app/comic-book-store/backend/node_modules/bcrypt/bcrypt.js:6:16)
2022-05-31T07:27:47.337380+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1105:14)
2022-05-31T07:27:47.337380+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
2022-05-31T07:27:47.337381+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-05-31T07:27:47.337381+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-05-31T07:27:47.337381+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-05-31T07:27:47.337381+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-05-31T07:27:47.337382+00:00 app[web.1]: at Object.<anonymous> (/app/comic-book-store/backend/routes/memberRoute.js:5:16)
2022-05-31T07:27:47.337382+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1105:14)
2022-05-31T07:27:47.337382+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
2022-05-31T07:27:47.337382+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32) {
2022-05-31T07:27:47.337383+00:00 app[web.1]: code: 'ERR_DLOPEN_FAILED'
2022-05-31T07:27:47.337383+00:00 app[web.1]: }
2022-05-31T07:27:47.491907+00:00 heroku[web.1]: Process exited with status 1
2022-05-31T07:27:47.544210+00:00 heroku[web.1]: State changed from starting to crashed
2022-05-31T07:27:49.659165+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sakura-comic-bookstore.herokuapp.com request_id=46ff615e-9342-4840-9138-8a6f99af5d6e fwd="151.210.168.207" dyno= connect= service= status=503 bytes= protocol=https
2022-05-31T07:27:50.267049+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sakura-comic-bookstore.herokuapp.com request_id=c6af9a12-05e7-4deb-85dc-1e9fec2933c6 fwd="151.210.168.207" dyno= connect= service= status=503 bytes= protocol=https
2022-05-31T07:28:10.739605+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sakura-comic-bookstore.herokuapp.com request_id=39a85204-136c-41e8-989a-ece16cabc887 fwd="151.210.168.207" dyno= connect= service= status=503 bytes= protocol=https
2022-05-31T07:28:11.279361+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sakura-comic-bookstore.herokuapp.com request_id=44901387-4b2b-42a4-a15a-7747bd663d52 fwd="151.210.168.207" dyno= connect= service= status=503 bytes= protocol=https
I did not use the MongoDB sandbox in Heroku, I just connect my project database in Mongo Atlas when I developing the project. I think my database has no problem connecting with the app, I am able to see the data in Heroku local, the CRUD operations work fine in Heroku local.
Another thing I am not sure is, at the beginning of creating this project, I attempted to configure the React, Webpack, and Babel, but my tutor told me just use the React boilerplate, so I remove the config file of the Webpack, but I think I have not completely removed the Webpack and Babel dependencies in the frontend and backend folders, I am not sure if that affect the deployment in Heroku.
I really want to get the deployment done, and I think I had tries a lot of ways that seems to work, please give me a hint of what to do. I have no idea why everything work on Heroku local but not the Heroku live!!
My code doesn't work when I deploy it to heroku
This seems to cover the same issue, try to delete node_modules folders, and uninstall and install bcrypt from the backend

React/Node.js/Nodemailer - Heroku App crashing with NPM Err & H10 Error Code

I am using Reactjs / Node.js / Express / Nodemailer
In summary part of React App contains a Contact Us page where one can send a message to me through email. To implement this, I created a Node.js server and used Express/Nodemailer to send emails through my React App.
Locally, everything works perfectly.
Now when I try to deploy my site to Heroku, it is always crashing. I have deployed over 20 times trying to fix it.
Here are the logs from Heroku:
2021-01-20T04:11:14.009662+00:00 app[web.1]: npm ERR! Failed at the website#0.1.0 start script.
2021-01-20T04:11:14.009749+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2021-01-20T04:11:14.015125+00:00 app[web.1]:
2021-01-20T04:11:14.015276+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2021-01-20T04:11:14.015359+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2021-01-20T04_11_14_010Z-debug.log
2021-01-20T04:11:14.083728+00:00 heroku[web.1]: Process exited with status 1
2021-01-20T04:11:14.125666+00:00 heroku[web.1]: State changed from starting to crashed
2021-01-20T04:11:16.373733+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=somewebsite.herokuapp.com request_id=63caf1d0-c590-4380-a83f-38d8672dcc84 fwd="68.56.183.245" dyno= connect= service= status=503 bytes= protocol=https
2021-01-20T04:11:16.727290+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=somewebsite.herokuapp.com request_id=e307edc5-9a84-4c3a-b410-9557c159bfa6 fwd="68.56.183.245" dyno= connect= service= status=503 bytes= protocol=https
2021-01-20T04:11:17.171315+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=somewebsite.herokuapp.com request_id=4b115236-0dec-4c9b-90ce-beb6dec9aab7 fwd="68.56.183.245" dyno= connect= service= status=503 bytes= protocol=https
2021-01-20T04:34:39.704107+00:00 heroku[web.1]: State changed from crashed to starting
2021-01-20T04:34:56.646013+00:00 heroku[web.1]: Starting process with command `npm start`
2021-01-20T04:35:02.786236+00:00 app[web.1]:
2021-01-20T04:35:02.786301+00:00 app[web.1]: > website#0.1.0 start /app
2021-01-20T04:35:02.786306+00:00 app[web.1]: > npm run build && node server/index.js
2021-01-20T04:35:02.786307+00:00 app[web.1]:
2021-01-20T04:35:03.490869+00:00 app[web.1]:
2021-01-20T04:35:03.490918+00:00 app[web.1]: > website#0.1.0 build /app
2021-01-20T04:35:03.490918+00:00 app[web.1]: > react-scripts build
2021-01-20T04:35:03.490919+00:00 app[web.1]:
2021-01-20T04:35:05.274051+00:00 app[web.1]: Creating an optimized production build...
2021-01-20T04:35:56.983483+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2021-01-20T04:35:57.008295+00:00 heroku[web.1]: Stopping process with SIGKILL
2021-01-20T04:35:57.036467+00:00 app[web.1]: Error waiting for process to terminate: No child processes
2021-01-20T04:35:57.118110+00:00 heroku[web.1]: Process exited with status 22
2021-01-20T04:35:57.152133+00:00 heroku[web.1]: State changed from starting to crashed
This is my package.json file:
{
"homepage": "/",
"name": "website",
"version": "0.1.0",
"private": true,
"dependencies": {
"#google/model-viewer": "^1.2.1",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"axios": "^0.21.1",
"bootstrap": "^4.5.2",
"classnames": "^2.2.6",
"cors": "^2.8.5",
"express": "^4.17.1",
"mailgen": "^2.0.13",
"mdbreact": "^4.27.0",
"nodemailer": "^6.4.17",
"react": "^16.13.1",
"react-bootstrap": "^1.3.0",
"react-dom": "^16.13.1",
"react-model-viewer": "^0.6.1",
"react-player": "^2.6.2",
"react-responsive-modal": "^6.0.0",
"react-router-dom": "^5.2.0",
"react-scripts": "^3.4.4",
"reactstrap": "^8.6.0",
"styled-components": "^5.2.0",
"three": "^0.120.1"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
"start": "npm run build && node server/index.js",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"start-server": "node server/index.js",
"start-app": "npm run build && npm run start-server"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.12.3",
"#babel/node": "^7.12.1",
"dotenv": "^8.2.0",
"gh-pages": "^3.1.0",
"puppeteer": "^5.3.1"
}
}
I believe my start script is correct, in regards to npm run build loading in my front-end and node server/index.js starting up my "Email Server".
Here is my index.js file:
const path = require('path');
const express = require('express');
const Mailgen = require('mailgen');
const transporter = require('./config');
const dotenv = require('dotenv');
dotenv.config();
const app = express();
const buildPath = path.join(__dirname, '..', 'build');
app.use(express.json());
app.use(express.static(buildPath));
app.post('/send', (req, res) => {
try {
const mailOptions = {
from: req.body.email, // sender address
to: process.env.email, // list of receivers
subject: 'New Message from Contact Us Form', // Subject line
html: `
<p>You have a new contact request.</p>
<h3>Contact Details</h3>
<ul>
<li>Name: ${req.body.name}</li>
<li>Email: ${req.body.email}</li>
<li>Phone: ${req.body.phone}</li>
<li>Company: ${req.body.company}</li>
<li>Message: ${req.body.message}</li>
</ul>
`
};
transporter.sendMail(mailOptions, function (err, info) {
if (err) {
res.status(500).send({
success: false,
message: 'Something went wrong. Try again later'
});
} else {
res.send({
success: true,
message: 'Thanks for contacting us. We will get back to you shortly'
});
}
});
} catch (error) {
res.status(500).send({
success: false,
message: 'Something went wrong. Try again later'
});
}
});
const mailGenerator = new Mailgen({
theme: 'default',
product: {
// Appears in header & footer of e-mails
name: 'Some Name',
link: 'https://website.live'
// Product logo
// logo: 'https://mailgen.js/img/logo.png'
}
});
app.post('/sendLaunch', (req, res) => {
try {
const mailOptions = {
from: req.body.emailLaunch, // sender address
to: process.env.email, // list of receivers
subject: 'New Sign-Up Customer', // Subject line
html: `
<p>You have a new Sign-Up contact.</p>
<h3>Contact Details</h3>
<ul>
<li>First Name: ${req.body.firstNameLaunch}</li>
<li>Last Name: ${req.body.lastNameLaunch}</li>
<li>Email: ${req.body.emailLaunch}</li>
</ul>
`
};
const responseLaunch = {
body: {
name: req.body.firstNameLaunch + " " + req.body.lastNameLaunch,
intro: "Thanks for signing up!"
}
}
const emailRespLaunch = mailGenerator.generate(responseLaunch);
const emailResponseLaunch = {
from: process.env.email,
to: req.body.emailLaunch,
subject: "You're Signed Up!",
html: emailRespLaunch,
};
transporter.sendMail(mailOptions, function (err, info) {
if (err) {
res.status(500).send({
success: false,
message: 'Something went wrong. Try again later'
});
} else {
res.send({
success: true,
message: 'Thanks for signing up.'
});
}
});
transporter.sendMail(emailResponseLaunch, function (err, info) {
if (err) {
res.status(500).send({
success: false
});
} else {
res.send({
success: true
});
}
});
} catch (error) {
res.status(500).send({
success: false,
message: 'Something went wrong. Try again later'
});
}
});
// App does not load properly locally without this snippet of code below
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '..', 'build', 'index.html'));
});
app.listen(process.env.PORT || 3030);
I have searched and rummaged through what feels like everything in regards to the issue and tried some solutions from similar issues found on stackoverflow but no luck yet.
Any help would be highly appreciated!

Heroku failing to bind PORT

const express = require('express')
const bodyParser = require('body-parser')
const nodemailer = require('nodemailer')
const path = require("path")
const cors = require('cors')
const ical = require('ical-generator')
require('dotenv').config()
const app = express()
const PORT = process.env.PORT || 3001;
const HOST = process.env.YOUR_HOST || '0.0.0.0'
app.use(express.urlencoded({extended:true}))
// app.use(bodyParser.json())
// app.use(bodyParser.urlencoded({extended:true}))
app.use(express.json());
app.use(cors())
if (process.env.NODE_ENV === "production") {
app.use("/react-portofolio/", express.static(path.join(__dirname, "client", "build")));
}
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
// app.use(express.static(path.join(__dirname, 'build')));
// app.get('/*', (req, res) => {
// res.sendFile(path.join(__dirname, 'build', 'index.html'));
// });
app.listen(PORT, HOST, () => {
console.log(`Example app listening at http://${HOST}:${ PORT }/`)
})
Sorry to bother. Similar question has been posted. However I have followed the instruction on 3 different forum but getting the same error when I push to heroku for deployment. Build succeeded but I get something already running on PORT
2020-12-08T04:17:26.884688+00:00 app[web.1]: [1] Something is already running on port 57232.
2020-12-08T04:17:27.006588+00:00 app[web.1]: [1] npm run client exited with code 0
2020-12-08T04:26:37.127662+00:00 heroku[router]: at=info method=GET path="/" host=discoversamir.herokuapp.com request_id=46d76b48-2724-4726-9db0-6a7e32aebfc3 fwd="70.119.31.93" dyno=web.1 connect=0ms service=48ms status=200 bytes=2779 protocol=https
2020-12-08T04:26:37.237894+00:00 heroku[router]: at=info method=GET path="/static/css/main.9a72c1e7.chunk.css" host=discoversamir.herokuapp.com request_id=2d0792e3-4cd4-4a05-a2a4-acc41070767d fwd="70.119.31.93" dyno=web.1 connect=0ms service=14ms status=200 bytes=2779 protocol=https
2020-12-08T04:26:37.239633+00:00 heroku[router]: at=info method=GET path="/static/js/2.2cea4fb7.chunk.js" host=discoversamir.herokuapp.com request_id=dfd7e060-3da6-4073-80cd-7499cf41456a fwd="70.119.31.93" dyno=web.1 connect=0ms service=16ms status=200 bytes=2779 protocol=https
2020-12-08T04:26:37.312361+00:00 heroku[router]: at=info method=GET path="/src/App.css" host=discoversamir.herokuapp.com request_id=739a09b6-4f5b-41e8-9c8a-fb05fd183303 fwd="70.119.31.93" dyno=web.1 connect=0ms service=13ms status=200 bytes=2779 protocol=https
2020-12-08T04:26:37.313463+00:00 heroku[router]: at=info method=GET path="/static/js/main.dff0b724.chunk.js" host=discoversamir.herokuapp.com request_id=2e3abec9-f772-4bc8-b74b-75016552c304 fwd="70.119.31.93" dyno=web.1 connect=1ms service=14ms status=200 bytes=2779 protocol=https
2020-12-08T04:26:37.399704+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=discoversamir.herokuapp.com request_id=921c7d52-76e6-4254-a9ab-cd8968dd8182 fwd="70.119.31.93" dyno=web.1 connect=0ms service=6ms status=200 bytes=2779 protocol=https
2020-12-08T04:26:37.556042+00:00 heroku[router]: at=info method=GET path="/manifest.json" host=discoversamir.herokuapp.com request_id=c58d231d-60c0-42e4-a714-30a20333a156 fwd="70.119.31.93" dyno=web.1 connect=0ms service=4ms status=200 bytes=2779 protocol=https
Here is my pacakage.JSON
"name": "react-portofolio",
"version": "1.0.0",
"description": "My portofolio",
"main": "server.js",
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
"test": "echo \"Error: no test specified\" && exit 1",
"start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
"start:prod": "node server.js",
"start:dev": "concurrently \"nodemon --ignore 'client/*'\" \"npm run client\"",
"client": "cd client && npm run start",
"install": "cd client && npm install",
"build": "cd client && npm run build",
"heroku-postbuild": "cd client && npm install && npm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/agnide4/react-portofolio.git"
},
"keywords": [
"portofolio",
"resume"
],
"author": "Samir Bello",
"license": "ISC",
"bugs": {
"url": "https://github.com/agnide4/react-portofolio/issues"
},
"homepage": "https://github.com/agnide4/react-portofolio#readme",
"dependencies": {
"body-parser": "^1.19.0",
"concurrently": "^5.3.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"ical-generator": "^1.15.2",
"nodemailer": "^6.4.16",
"nodemon": "^2.0.6"
},
"devDependencies": {
"gh-pages": "^3.1.0"
},
"engines": {
"node": "12.8.0",
"npm": "6.14.9"
}
It keeps giving me a manifest.JSON error`.
repo is https://github.com/agnide4/react-portofolio . Please point me to the direction of what I am missing.
Try changing this in your server.js file
app.listen(PORT, HOST, () => {
console.log(`Example app listening at http://localhost:${PORT}`)
})
This, And also try removing the HOST declaration and process.env.HOST
app.listen(PORT, () => {
console.log(`Example app listening at http://localhost:${PORT}`)
})
Heroku assigns ports dynamically to your Node process. This should be available for use in process.env.PORT — if you want to have a default for running when none is set (ex. 8000) I'd make sure that your code is doing something like:
const port = process.env.PORT || 8000
and then passing port to your app.listen function.

Node & Heroku: Fails at start script, but works perfectly on my local machine

I am working on deploying Net Ninja's JWT authentication tutorial/project to heroku, but I am getting an error that I have not been able to overcome. This application works perfectly on my local computer. So far I've read through several stack overflow questions, but every fix for this issue that I've come across, I have already implemented.
Here are the heroku logs of my error.
2020-12-03T16:22:13.292858+00:00 app[web.1]: npm ERR!
2020-12-03T16:22:13.292982+00:00 app[web.1]: npm ERR! Failed at the node-express-jwt-auth#1.0.0 start script.
2020-12-03T16:22:13.293125+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-12-03T16:22:13.300898+00:00 app[web.1]:
2020-12-03T16:22:13.301049+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-12-03T16:22:13.301127+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2020-12-03T16_22_13_293Z-debug.log
2020-12-03T16:22:13.432936+00:00 heroku[web.1]: Process exited with status 1
2020-12-03T16:22:13.479796+00:00 heroku[web.1]: State changed from starting to crashed
2020-12-03T18:29:03.230278+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=net-ninja-jwt-tutorial.herokuapp.com request_id=b693f181-6061-4704-ad14-08b71b6b0cb0 fwd="208.102.105.218" dyno= connect= service= status=503 bytes= protocol=https
2020-12-03T18:29:04.077018+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=net-ninja-jwt-tutorial.herokuapp.com request_id=d363fc10-2e07-4e50-a024-c9f848b19c42 fwd="208.102.105.218" dyno= connect= service= status=503 bytes= protocol=https
My package.json is as follows:
{
"name": "node-express-jwt-auth",
"version": "1.0.0",
"description": "",
"main": "app.js",
"dependencies": {
"bcrypt": "^5.0.0",
"dotenv": "^8.2.0",
"ejs": "^3.1.3",
"express": "^4.17.1",
"mongoose": "^5.9.23",
"validator": "^13.1.17"
},
"devDependencies": {},
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/iamshaunjp/node-express-jwt-auth.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/iamshaunjp/node-express-jwt-auth/issues"
},
"engine":{
"node":"12.x"
}
}
My app.js file reads as follows:
const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config()
// import cookie parser
const cookieParser = require('cookie-parser');
// import require auth
const {requireAuth, checkUser} = require('./middleware/authMiddleware')
// import authRoutes
const authRoutes = require('./routes/authRoutes')
const app = express();
const port = process.env.PORT || 3000
// middleware
app.use(express.static('public'));
// below allows us to use JSON in our requests
app.use(express.json());
// allows us to use cookieParser as middleware
app.use(cookieParser());
// view engine
app.set('view engine', 'ejs');
// database connection
const dbURI = 'mongodb+srv://david:Looping!#nodeauth.uj5ph.mongodb.net/<dbname>?retryWrites=true&w=majority';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true })
.then((result) => {
app.listen(port)
console.log(`listening on port ${port}`)
})
.catch((err) => console.log(err));
// routes
//
app.get('*', checkUser);
app.get('/', (req, res) => res.render('home'));
app.get('/smoothies', requireAuth, (req, res) => res.render('smoothies'));
// allow us to import are authroutes into the app.js file.
app.use(authRoutes)
// cookies routes
// app.get('/set-cookies', (req, res) =>{
// // res.setHeader('Set-Cookie','newUser=true')
// // npm install cookie-parser
// res.cookie("newUser", false);
// res.cookie("isEmployee", true, {maxAge:1000*60*60*24, httpOnly:true});
// res.send('you got the cookies!');
// });
// app.get('/read-cookies', (req, res) =>{
// const cookies = req.cookies;
// console.log(cookies)
// res.json(cookies)
// });
Lastly, my procfile reads:
web:node app.js
If anyone were able to help me out with this, it would be a very big help.
On a side note, when my heroku logs read:
2020-12-03T16:22:13.301049+00:00 app[web.1]: npm ERR! A complete log
of this run can be found in: 2020-12-03T16:22:13.301127+00:00
app[web.1]: npm ERR!
/app/.npm/_logs/2020-12-03T16_22_13_293Z-debug.log
How would I go about accessing those error logs?
Edit: after running
$heroku logs --app net-ninja-jwt-tutorial
I disovered the following error:
2020-12-03T19:50:24.064213+00:00 app[web.1]: Error: Cannot find module 'cookie-parser'
There's a lot more to the logs, but I /think/ this is the relevant issue. However, this confuses me, I have cookie-parser in my package.json file.

Unable to deploy Contact Page Backend in Node.js to Heroku

I wrote backend in Node.js for the contact page on my portfoilio on Firebase. I'm trying to deploy it, but when open the app, it gives me an 'Application Error'. When I go to the logs, it gives me error code=H10 desc="App crashed".
Update: I also see an error Error: Cannot find module '#sendGrid/mail'.
I've tried a few things. I added "start": "node App.js" and "engines": { "node": "12.13.1" } to my package.json. I created a Procfile with web: node App.js. In my App.js, I changed my app.listen(4000, '0.0.0.0'); to app.listen(process.env.PORT || 4000);.
I'm not sure if I have to set process.env.PORT to something. How would I fix this?
Relevant Code
App.js
const express = require('express'); //Needed to launch server.
const bodyParser = require('body-parser');
const cors = require('cors'); //Needed to disable sendgrid security.
const sendGrid = require('#sendGrid/mail'); //Access SendGrid library to send emails.
sendGrid.setApiKey(process.env.SENDGRID_API_KEY);
const app = express(); //Alias from the express function.
app.use(bodyParser.json());
app.use(cors());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
app.get('/api', (req, res, next) => {
res.send('API Status: Running');
});
app.post('/api/email', (req, res, next) => {
console.log(req.body);
const msg = {
to: 'my#email.com',
from: req.body.email,
subject: req.body.subject,
text: req.body.message
}
sendGrid.send(msg)
.then(result => {
res.status(200).json({
success: true
});
})
.catch(err => {
console.log('error: ', err);
res.status(401).json({
success: false
});
});
});
app.listen(process.env.PORT || 4000);
Also, here's my package.json
{
"name": "my-app-api",
"version": "1.0.0",
"description": "",
"main": "App.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node App.js"
},
"author": "Daniel Zhang",
"license": "ISC",
"dependencies": {
"#sendgrid/mail": "^7.2.2",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"nodemon": "^2.0.4"
},
"engines": {
"node": "12.13.1"
},
"devDependencies": {}
}
Also, here are the Application Logs:
2020-08-30T14:49:33.088197+00:00 heroku[web.1]: Starting process with command `node index.js`
2020-08-30T14:49:35.380821+00:00 heroku[web.1]: Process exited with status 1
2020-08-30T14:49:35.420886+00:00 heroku[web.1]: State changed from starting to crashed
2020-08-30T14:49:35.328408+00:00 app[web.1]: internal/modules/cjs/loader.js:800
2020-08-30T14:49:35.328435+00:00 app[web.1]: throw err;
2020-08-30T14:49:35.328436+00:00 app[web.1]: ^
2020-08-30T14:49:35.328436+00:00 app[web.1]:
2020-08-30T14:49:35.328437+00:00 app[web.1]: Error: Cannot find module '#sendGrid/mail'
2020-08-30T14:49:35.328437+00:00 app[web.1]: Require stack:
2020-08-30T14:49:35.328437+00:00 app[web.1]: - /app/index.js
2020-08-30T14:49:35.328438+00:00 app[web.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:797:15)
2020-08-30T14:49:35.328438+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:690:27)
2020-08-30T14:49:35.328439+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:852:19)
2020-08-30T14:49:35.328439+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:74:18)
2020-08-30T14:49:35.328439+00:00 app[web.1]: at Object.<anonymous> (/app/index.js:4:18)
2020-08-30T14:49:35.328440+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:959:30)
2020-08-30T14:49:35.328440+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
2020-08-30T14:49:35.328440+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:815:32)
2020-08-30T14:49:35.328441+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:727:14)
2020-08-30T14:49:35.328441+00:00 app[web.1]: at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10) {
2020-08-30T14:49:35.328441+00:00 app[web.1]: code: 'MODULE_NOT_FOUND',
2020-08-30T14:49:35.328442+00:00 app[web.1]: requireStack: [ '/app/index.js' ]
2020-08-30T14:49:35.328442+00:00 app[web.1]: }
2020-08-30T14:49:46.278674+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/api" host=daniel-zhang-portfolio-backend.herokuapp.com request_id=b50170d2-6e1f-4697-aa35-3ea445d1d936 fwd="75.75.104.235" dyno= connect= service= status=503 bytes= protocol=https
2020-08-30T14:49:46.490432+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=daniel-zhang-portfolio-backend.herokuapp.com request_id=cb1bdef2-0cb6-400d-aaf5-e8e2c2b8fa35 fwd="75.75.104.235" dyno= connect= service= status=503 bytes= protocol=https
Also here's my file structure:
In const sendGrid = require('#sendGrid/mail');, '#sendGrid/mail' should be '#sendgrid/mail'.
I'm posting this answer because I was getting the same error message. However, the issue was not related to the case import/require statement.
The error i was facing was following (Error: Cannot find module '#sendgrid/mail')
However, my application was running locally without any errors, as #sendgrid/mail was present inside my node_modules folder.
So what was the culprit?
Thw issue was inside my package.json file, as it was not present inside it as a dependency.
Solution
I ran the following commands inside my Vs code terminal.
npm install #sendgrid/mail
git add .
git commit -m "my fix"
git push heroku master
Note: you may update the push command according to your branch, in my case it was master.

Resources