Beginner with node.js I have an issue to deploy server on heroku.
I made a server.js application which use mongodb.
It's work fine when I run the server on local (http://localhost:3000) with "npm start" cmd, I'm able to connect to my mongo database by the command :
mongoose.connect(
'mongodb+srv://yolanpibrac:mypassword#cluster0-7z1th.mongodb.net/test? retryWrites=true&w=majority';,
{ useNewUrlParser: true })
(I followed this tutorial : [https://appdividend.com/2018/04/14/how-to-deploy-nodejs-app-to-heroku/])
But when i deploy my app on heroku, the app can not connect to mongo db. I have the following error (by checking : heroku logs -t) :
2019-08-06T21:06:33.086146+00:00 heroku[web.1]: Starting process with command `node src/server.js`
2019-08-06T21:06:35.404641+00:00 heroku[web.1]: State changed from starting to up
2019-08-06T21:06:35.058357+00:00 app[web.1]: Listening on port 26845
2019-08-06T21:06:36.144056+00:00 app[web.1]: Error while DB connecting
2019-08-06T21:06:36.149809+00:00 app[web.1]: { MongoNetworkError: failed to connect to server [cluster0-shard-00-00-7z1th.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to cluster0-shard-00-00- 7z1th.mongodb.net:27017 closed]
2019-08-06T21:06:36.149812+00:00 app[web.1]: at Pool.<anonymous> (/app/node_modules/mongodb-core/lib/topologies/server.js:431:11)
2019-08-06T21:06:36.149814+00:00 app[web.1]: at Pool.emit (events.js:189:13)
2019-08-06T21:06:36.149815+00:00 app[web.1]: at connect (/app/node_modules/mongodb-core/lib/connection/pool.js:557:14)
2019-08-06T21:06:36.149816+00:00 app[web.1]: at callback (/app/node_modules/mongodb-core/lib/connection/connect.js:109:5)
2019-08-06T21:06:36.149818+00:00 app[web.1]: at runCommand (/app/node_modules/mongodb-core/lib/connection/connect.js:129:7)
2019-08-06T21:06:36.149819+00:00 app[web.1]: at Connection.errorHandler (/app/node_modules/mongodb-core/lib/connection/connect.js:321:5)
2019-08-06T21:06:36.149820+00:00 app[web.1]: at Object.onceWrapper (events.js:277:13)
2019-08-06T21:06:36.149821+00:00 app[web.1]: at Connection.emit (events.js:189:13)
2019-08-06T21:06:36.149823+00:00 app[web.1]: at TLSSocket.<anonymous> (/app/node_modules/mongodb-core/lib/connection/connection.js:350:12)
2019-08-06T21:06:36.149824+00:00 app[web.1]: at Object.onceWrapper (events.js:277:13)
2019-08-06T21:06:36.149825+00:00 app[web.1]: at TLSSocket.emit (events.js:189:13)
2019-08-06T21:06:36.149826+00:00 app[web.1]: at _handle.close (net.js:613:12)
2019-08-06T21:06:36.149828+00:00 app[web.1]: at TCP.done (_tls_wrap.js:386:7)
2019-08-06T21:06:36.149829+00:00 app[web.1]: name: 'MongoNetworkError',
2019-08-06T21:06:36.149830+00:00 app[web.1]: errorLabels: [ 'TransientTransactionError' ],
2019-08-06T21:06:36.149832+00:00 app[web.1]: [Symbol(mongoErrorContextSymbol)]: {} }
I already read all issues related to this problem, but none of the solution worked.
I have mongodb account with cluster connexion string
I was carefull in my password that any special characters are URL encoded.
I have a procfile : web: node src/server.js and an index.html file
my server.js file :
//Définition des modules
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require('body-parser');
const app = express();
const path = require('path');
const dbRoute = 'mongodb+srv://yolanpibrac:mypassword#cluster0- 7z1th.mongodb.net/test?retryWrites=true&w=majority';
const dbRouteLocal = 'mongodb://localhost/db';
//Connexion à la base de donnée
mongoose.connect(dbRoute, { useNewUrlParser: true }).then(() => {
console.log('Connected to mongoDB')
}).catch(e => {
console.log('Error while DB connecting');
console.log(e);
});
var urlencodedParser = bodyParser.urlencoded({
extended: true
});
app.use(urlencodedParser);
app.use(bodyParser.json({limit: '10mb', extended: true}));
//Définition des CORS
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Headers', 'Origin,X-Requested- With,content-type,Accept,content-type,application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
var router = express.Router();
app.use('/user', router);
require(__dirname + '/controllers/userController')(router);
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
//Définition et mise en place du port d'écoute
var port = process.env.PORT || "3000";
app.listen(port, () => console.log(`Listening on port ${port}`));
my package.json :
{
"name": "movies-displayer",
"version": "0.1.0",
"engines": {
"node": "11.4.0"
},
"private": true,
"proxy": "http://yolan-pibrac.com",
"dependencies": {
"animated": "^0.2.2",
"axios": "^0.19.0",
"body-parser": "^1.19.0",
"bootstrap": "^4.3.1",
"express": "^4.17.1",
"jwt-simple": "^0.5.6",
"mongodb": "^3.3.0-beta2",
"mongoose": "^5.6.8",
"password-hash": "^1.2.2",
"react": "^16.8.6",
"react-activity": "^1.2.2",
"react-animations": "^1.0.0",
"react-bootstrap": "^0.32.1",
"react-bootstrap-dropdown-menu": "^1.1.15",
"react-dom": "^16.8.6",
"react-multi-carousel": "^2.1.2",
"react-popper": "^1.3.3",
"react-pose": "^4.0.8",
"react-redux": "^7.0.3",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"react-scripts": "3.0.1",
"react-state-animation": "^0.1.0",
"reactstrap": "^8.0.1",
"redux": "^4.0.1",
"styled-components": "^4.3.2"
},
"scripts": {
"start": "node src/server.js"
},
"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"
]
}
}
I can provide more details if needed !
Thank you for your help,
You may need to allow heroku to access your mongodb server.
You can do this by logging in to Mongodb atlas and clicking on Network access on the left side under security settings, then click add ip address on the right top and enter 0.0.0.0/0 as the ip address to allow access from all ip's a or add your heroku servers' specific ip if you can get it.
Related
I'm trying to run my node server run, but suddenly i have got this error. How can i solve this error? when i command npm run start-dev show me this error. i have change this port, but got same error. Why happend this error? Please help me out, how can i solve this?
here is the error,
node:events:491
throw er; // Unhandled 'error' event
^
Error: listen EACCES: permission denied 30000;
at Server.setupListenHandle [as _listen2] (node:net:1468:21)
at listenInCluster (node:net:1533:12)
at Server.listen (node:net:1632:5)
at Function.listen (D:\ecommerce-api\node_modules\express\lib\application.js:635:24)
at StartDB (D:\ecommerce-api\app.js:34:9)
at Object.<anonymous> (D:\ecommerce-api\app.js:42:1)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1512:8)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'EACCES',
errno: -4092,
syscall: 'listen',
address: '5000;',
port: -1
}
Node.js v18.12.1
[nodemon] app crashed - waiting for file changes before starting...
my env file
PORT=5000;
MONGO_URI=mongodb://127.0.0.1:27017/ecommerce
App js file
require("dotenv").config();
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
//Database
const connectDB = require("./DB/ConnectDB");
//Paths
const authRoute = require("./Routes/AuthRoute");
//Middleware
app.use(express.json());
app.get("/", (req, res) => {
res.send("Ecommerce API!");
});
app.use("/api/v1/auth", authRoute);
const StartDB = async () => {
try {
connectDB(process.env.MONGO_URI);
app.listen(port, () => {
console.log(`App listening on port ${port}`);
});
} catch (error) {
console.log(error);
}
};
StartDB();
the package json file below.
my pacakge json file
{
"name": "ecommerce-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js",
"start-dev": "nodemon app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-async-errors": "^3.1.1",
"http-status-codes": "^2.2.0",
"jsonwebtoken": "^9.0.0",
"mongoose": "^6.8.4",
"morgan": "^1.10.0",
"validator": "^13.7.0"
}
}
I got the same error , do not add any spaces in (.env) file , then you should get the answer
I am having issues deploying to Heroku. I have uploaded the relevant env variables under "Config Vars" within Heroku Dashboard but am wondering why I am still getting hit with the following error below:
2022-07-22T06:47:59.068313+00:00 heroku[web.1]: Starting process with command `npm start`
2022-07-22T06:48:00.732711+00:00 app[web.1]:
2022-07-22T06:48:00.732804+00:00 app[web.1]: > project-management-webapp#1.0.0 start
2022-07-22T06:48:00.732804+00:00 app[web.1]: > npm install && cd server && node index.js
2022-07-22T06:48:00.732805+00:00 app[web.1]:
2022-07-22T06:48:01.693914+00:00 app[web.1]:
2022-07-22T06:48:01.693932+00:00 app[web.1]: up to date, audited 128 packages in 601ms
2022-07-22T06:48:01.694072+00:00 app[web.1]:
2022-07-22T06:48:01.694106+00:00 app[web.1]: 14 packages are looking for funding
2022-07-22T06:48:01.694126+00:00 app[web.1]: run `npm fund` for details
2022-07-22T06:48:01.695406+00:00 app[web.1]:
2022-07-22T06:48:01.695406+00:00 app[web.1]: found 0 vulnerabilities
2022-07-22T06:48:02.296149+00:00 heroku[web.1]: State changed from starting to crashed
2022-07-22T06:48:02.083051+00:00 app[web.1]: Server running on port 24830
2022-07-22T06:48:02.087994+00:00 app[web.1]: /app/node_modules/mongodb-connection-string-url/lib/index.js:86
2022-07-22T06:48:02.088006+00:00 app[web.1]: throw new MongoParseError('Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"');
2022-07-22T06:48:02.088007+00:00 app[web.1]: ^
2022-07-22T06:48:02.088007+00:00 app[web.1]:
2022-07-22T06:48:02.088013+00:00 app[web.1]: MongoParseError: Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"
2022-07-22T06:48:02.088013+00:00 app[web.1]: at new ConnectionString (/app/node_modules/mongodb-connection-string-url/lib/index.js:86:19)
2022-07-22T06:48:02.088014+00:00 app[web.1]: at parseOptions (/app/node_modules/mongodb/lib/connection_string.js:209:17)
2022-07-22T06:48:02.088014+00:00 app[web.1]: at new MongoClient (/app/node_modules/mongodb/lib/mongo_client.js:62:63)
2022-07-22T06:48:02.088015+00:00 app[web.1]: at /app/node_modules/mongoose/lib/connection.js:796:16
2022-07-22T06:48:02.088015+00:00 app[web.1]: at new Promise (<anonymous>)
2022-07-22T06:48:02.088016+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:793:19)
2022-07-22T06:48:02.088016+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:379:10
2022-07-22T06:48:02.088016+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
2022-07-22T06:48:02.088016+00:00 app[web.1]: at new Promise (<anonymous>)
2022-07-22T06:48:02.088021+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
2022-07-22T06:48:02.228355+00:00 heroku[web.1]: Process exited with status 1
Below is the relevant code:
INDEX.JS
const express = require('express')
const colors = require('colors')
const { graphqlHTTP } = require('express-graphql')
const cors = require('cors')
const schema = require('./schema/schema')
const connectDB = require('./config/db')
require('dotenv').config()
const app = express()
// MongoDB
connectDB()
// CORS
app.use(cors())
// GraphQL
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
graphiql: process.env.NODE_ENV === 'development',
})
)
app.listen(
process.env.PORT || 4000,
console.log(`Server running on port ${process.env.PORT}`)
)
DB.JS
const mongoose = require('mongoose')
const connectDB = async () => {
const conn = await mongoose.connect(process.env.MONGODB_URI)
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline.bold)
}
module.exports = connectDB
PACKAGE.JSON
{
"name": "project-management-webapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "npm install && cd server && node index.js",
"dev": "nodemon server/index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/BIGWALDOR/project-management-webapp.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/BIGWALDOR/project-management-webapp/issues"
},
"homepage": "https://github.com/BIGWALDOR/project-management-webapp#readme",
"dependencies": {
"colors": "^1.4.0",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"express-graphql": "^0.12.0",
"graphql": "^15.8.0",
"mongoose": "^6.4.5"
},
"devDependencies": {
"nodemon": "^2.0.19"
}
}
I'm definitely at a loss here so any help would be much appreciated!
I am Trying To deploy, my MERN stack app on the digital ocean,
fronted is working Ok,
I have a problem with backend server.js, I am using "type": "module" in package.json,
Getting This error
code: 'ERR_REQUIRE_ESM'
7|server | }
7|server | Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /var/www/html/backend/server.js
7|server | at Object.Module._extensions..js (internal/modules/cjs/loader.js:1015:13)
7|server | at Module.load (internal/modules/cjs/loader.js:863:32)
7|server | at Function.Module._load (internal/modules/cjs/loader.js:708:14)
7|server | at Object.<anonymous> (/usr/lib/node_modules/pm2/lib/ProcessContainerFork.js:32:23)
7|server | at Module._compile (internal/modules/cjs/loader.js:999:30)
7|server | at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
7|server | at Module.load (internal/modules/cjs/loader.js:863:32)
7|server | at Function.Module._load (internal/modules/cjs/loader.js:708:14)
7|server | at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
7|server | at internal/main/run_main_module.js:17:47 {
7|server | code: 'ERR_REQUIRE_ESM'
7|server | }
This is How My packacge.json looks
{
"name": "obstacle-sports",
"version": "1.0.0",
"description": "Obstacle-Sports App",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node backend/server",
"server": "nodemon backend/server",
"client": "npm start --prefix frontend",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
"author": "Shmagi",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cloudinary": "^1.25.0",
"colors": "^1.4.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-async-handler": "^1.1.4",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.11.13",
"multer": "^1.4.2"
},
"devDependencies": {
"concurrently": "^5.3.0",
"nodemon": "^2.0.4"
}
}
and this is my server.js
import path from 'path'
import express from 'express'
import dotenv from 'dotenv'
import colors from 'colors'
import { notFound, errorHandler } from './middleware/errorMiddlleware.js'
import connectDB from './config/db.js'
import eventRouter from './routes/eventsRoute.js'
import blogRouter from './routes/blogRoute.js'
import userRouter from './routes/userRoutes.js'
import uploadRouter from './routes/uploadRoutes.js'
dotenv.config()
connectDB()
const app = express()
app.use(express.json())
app.use('/api/events', eventRouter)
app.use('/api/blogs', blogRouter)
app.use('/api/users', userRouter)
app.use('/api/uploads', uploadRouter)
const __dirname = path.resolve()
app.use('/uploads', express.static(path.join(__dirname, '/uploads')))
if(process.env.NODE_ENV === 'production'){
app.use(express.static(path.join(__dirname, '/frontend/build')))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'))
})
} else {
app.get('/', (req, res) => {
res.send('App Is Running...')
})
}
app.use(notFound)
app.use(errorHandler)
const PORT = process.env.PORT || 5000
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.listen(5000, () => {
console.log(`Server Is Running In ${process.env.NODE_ENV} Mode On Port ${PORT}`.yellow.bold)
})
can anyone help? any ideas?
here is my frontend is running ok, but if you go to http://104.236.106.171/events it will cause an error, :((
http://104.236.106.171/
and on local it is working Ok
I'm getting this error when unit testing code,
2 passing (14ms) 1 failing
1) Uncaught error outside test suite:
Uncaught Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (net.js:1255:14)
at listenInCluster (net.js:1303:12)
at Server.listen (net.js:1391:7)
at Function.listen (node_modules/express/lib/application.js:618:24)
at Object.listen (main.js:39:5)
at Module._compile (internal/modules/cjs/loader.js:721:30)
at Module._compile (node_modules/pirates/lib/index.js:99:24)
at Module._extensions..js (internal/modules/cjs/loader.js:732:10)
at Object.newLoader [as .js] (node_modules/pirates/lib/index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Module.require (internal/modules/cjs/loader.js:657:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object. (test/main.test.js:4:1)
at Module._compile (internal/modules/cjs/loader.js:721:30)
at Module._compile (node_modules/pirates/lib/index.js:99:24)
at Module._extensions..js (internal/modules/cjs/loader.js:732:10)
at Object.newLoader [as .js] (node_modules/pirates/lib/index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Module.require (internal/modules/cjs/loader.js:657:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Array.forEach ()
at StatWatcher.onchange (internal/fs/watchers.js:50:8)
I'm using mocha, and i have --watch on my package.json. I'm using an es6 approach to express.
Package.json
{
"name": "elies6express",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "./node_modules/.bin/mocha --watch --require #babel/register",
"start": "nodemon --exec babel-node main.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"bookshelf": "^0.14.2",
"chai-http": "^4.3.0",
"cookie-parser": "^1.4.4",
"cors": "^2.8.5",
"dotenv": "^8.0.0",
"express": "^4.17.0",
"knex": "^0.16.5",
"morgan": "^1.9.1",
"path": "^0.12.7",
"pg": "^7.11.0"
},
"devDependencies": {
"#babel/cli": "^7.4.4",
"#babel/core": "^7.4.5",
"#babel/node": "^7.4.5",
"#babel/preset-env": "^7.4.5",
"#babel/register": "^7.4.4",
"chai": "^4.2.0",
"mocha": "^6.1.4",
"nodemon": "^1.19.0",
"reify": "^0.19.1",
"request": "^2.88.0"
}
}
main.js
import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from 'morgan';
import path from 'path';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import userRoute from './routes/users';
const app = express();
app.use(cors());
app.use(logger('dev'));
// For React Stuff if need be
// app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
app.use(cookieParser());
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.use('/users', userRoute);
app.use(() => (req, res, next) =>{
res.locals.user = req.user; // This is the important line
// req.session.user = user
console.log(res.locals.user);
next();
});
app.use(bodyParser.urlencoded({ extended:false}));
//build mode
// app.get('*', (req, res) => {
// res.sendFile(path.join(__dirname+'/client/public/index.html'));
// })
app.listen(process.env.PORT, () =>
console.log(`Example app listening on port ${process.env.PORT}!`),
);
export default app;
main.test.js
import chai from "chai"
import chaiHttp from 'chai-http';
import request from 'request';
import server from '../main';
const expect = chai.expect;
const should = chai.should();
chai.use(chaiHttp);
// should get /
describe('should GET /', () => {
it('should get 200 status', (done) =>{
chai.request(server)
.get('/')
.end( (err, res) => {
res.should.have.status(200);
done();
});
});
})
// should check for Hello World!
describe('Should check for Hello World! text', () => {
it('should check for hello world text', (done) =>{
chai.request(server)
.get('/')
.end( (err, res) => {
expect(res.body).to.be.an('object') // works
expect(res.text).to.equal('Hello World!') // use res.text to check for res.send() text
done();
})
})
})
In main.js, place your app.listen call inside a test for !module.parent, like this:
if(!module.parent){
app.listen(process.env.PORT, () =>
console.log(`Example app listening on port ${process.env.PORT}!`),
);
}
Source: http://www.marcusoft.net/2015/10/eaddrinuse-when-watching-tests-with-mocha-and-supertest.html
The earlier linked
if (!module.parent) {
is deprecated as of v14.6.0, v12.19.0. (documentation link)
One solution is to use the following:
if (require.main === module) {
"testwatch": "nodemon --exec \"mocha --recursive\""
will 100% server your purpose until test library posts something more relevant
This looks very hacky, but what worked for me was making sure that, for every suite of tests, I would be using a different port.
It means that something is running on port 3000 already. You need to stop that and then start your application. Or just change the port of your application to something else.
To free up port 3000 use :
fuser -k 3000/tcp
or
kill $(sudo lsof -t -i:3000)
To change the port of your application :
var port = 8000;
app.listen(port, () =>
console.log(`Example app listening on port ${port}!`),
);
I am attempting to deploy a test express app on Heroku.
My package.json looks like this -
{
"name": "heroku-test-app",
"version": "1.0.0",
"description": "",
"main": "dist",
"scripts": {
"test": "cross-env NODE_ENV=test nodemon --exec mocha ./**/*.spec.js --compilers js:babel-core/register --require babel-polyfill",
"dev": "nodemon -w src --exec \"babel-node src --presets es2015,stage-0\"",
"build": "babel src -s -D -d dist --presets es2015,stage-0",
"start": "cross-env node dist",
"prestart": "npm run -s build",
"clean": "rimraf dist/"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-eslint": "^7.2.3",
"babel-polyfill": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"body-parser": "^1.17.2",
"cross-env": "^5.0.5",
"dotenv": "^4.0.0",
"express": "^4.15.4",
"morgan": "^1.8.2"
},
"devDependencies": {
"chai": "^4.1.1",
"mocha": "^3.5.0",
"nodemon": "^1.11.0",
"rimraf": "^2.6.1",
"supertest": "^3.0.0"
}
}
My Procfile looks like this -
web: npm start
and my test app is as so -
import express from 'express';
import morgan from 'morgan';
import bodyParser from 'body-parser';
const app = express();
const postBodyLimit = '100kb';
const port = 3000;
app.use(
morgan('combined', {
skip: (req, res) => res.statusCode < 400
})
);
app.use(bodyParser.json({ limit: postBodyLimit }));
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => res.status(200).json({ message: 'No unicorns here.' }));
// catch 404's and pass to our global error handler
app.all('*', (req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
res.status(err.status || 500).json({
message: err.message,
error: app.get('env') === 'development' ? err : null
});
});
app.listen(port, () => console.log(`listening on port ${port}`));
export default app;
When running my app locally, it starts and works perfectly. When running heroku local web, it also works as expected.
When I deploy to heroku however, I get the application error page. However on streaming my logs, there is nothing to suggest it has crashed.
I have just deployed again now, this is the current log file
2017-08-28T06:38:40.000000+00:00 app[api]: Build succeeded
2017-08-28T06:39:03.959631+00:00 app[web.1]:
2017-08-28T06:39:03.959649+00:00 app[web.1]: > heroic-test-app#1.0.0 prestart /app
2017-08-28T06:39:03.959650+00:00 app[web.1]: > npm run -s build
2017-08-28T06:39:03.959651+00:00 app[web.1]:
2017-08-28T06:39:05.856118+00:00 app[web.1]: src/index.js -> dist/index.js
2017-08-28T06:39:05.898228+00:00 app[web.1]:
2017-08-28T06:39:05.898232+00:00 app[web.1]: > heroic-test-app#1.0.0 start /app
2017-08-28T06:39:05.898234+00:00 app[web.1]: > cross-env node dist
2017-08-28T06:39:05.898234+00:00 app[web.1]:
2017-08-28T06:39:06.654100+00:00 app[web.1]: listening on port 3000
2017-08-28T06:44:40.078283+00:00 app[web.1]:
2017-08-28T06:44:40.078319+00:00 app[web.1]: > heroic-test-app#1.0.0 prestart /app
2017-08-28T06:44:40.078320+00:00 app[web.1]: > npm run -s build
2017-08-28T06:44:40.078321+00:00 app[web.1]:
2017-08-28T06:44:42.379605+00:00 app[web.1]: src/index.js -> dist/index.js
2017-08-28T06:44:42.434704+00:00 app[web.1]:
2017-08-28T06:44:42.434707+00:00 app[web.1]: > heroic-test-app#1.0.0 start /app
2017-08-28T06:44:42.434708+00:00 app[web.1]: > cross-env node dist
2017-08-28T06:44:42.434709+00:00 app[web.1]:
2017-08-28T06:44:43.156940+00:00 app[web.1]: listening on port 3000
2017-08-28T06:45:39.332668+00:00 app[web.1]: Error waiting for process to terminate: No child processes
I am at a loss how to proceed at this point.
you shouldn't set the port of http server as 3000, you should use the port of process.env, heroku will set an PORT in process.env.
So you should use app.listen(process.env.PORT, () => {}).
and there is an err code about the heroku application, if you can provide that, it would be better.