Node.js web app crashes when deployed to heroku - node.js

This problem has probably been posted about a dozen times, but I can't find a single fix to my problem.
Here is my code:
//////////////////// VARIABLES ////////////////////
//use express
var express = require('express');
//variable to use express
var app = express();
//use the body-parser middleware to handle post data
var bodyParser = require('body-parser');
//create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//create a variable for the server
//var server = require('http').Server(app)//
//////////////////// SETUP ////////////////////
//tells express to use ejs as the view/template engine
app.set('view engine', 'ejs');
//use express as middleware to serve static pages
app.use('/CSS', express.static('CSS'));
app.use('/images', express.static('images'));
//////////////////// FUNCTIONALITY ////////////////////
//sets index as the default page
app.get('/', function (req, res) {
res.render('index');
});
//serve specified pages
app.get('/:page', function (req, res) {
res.render(req.params.page);
});
app.post('/custom_rec', urlencodedParser, function (req, res) {
console.log(req.body);
res.render('custom_rec', {data: req.body});
});
const host = '0.0.0.0';
const port = process.env.PORT || 5000;
app.listen(port, host, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
Here are the relevant logs:
2018-10-23T08:42:25.388218+00:00 heroku[web.1]: State changed from crashed to starting
2018-10-23T08:42:30.109913+00:00 heroku[web.1]: Starting process with command `node ./index.js`
2018-10-23T08:42:33.503841+00:00 heroku[web.1]: Process exited with status 1
2018-10-23T08:42:33.525464+00:00 heroku[web.1]: State changed from starting to crashed
2018-10-23T08:42:33.439948+00:00 app[web.1]: module.js:549
2018-10-23T08:42:33.439965+00:00 app[web.1]: throw err;
2018-10-23T08:42:33.439967+00:00 app[web.1]: ^
2018-10-23T08:42:33.439968+00:00 app[web.1]:
2018-10-23T08:42:33.439970+00:00 app[web.1]: Error: Cannot find module '/app/index.js'
2018-10-23T08:42:33.439972+00:00 app[web.1]: at Function.Module._resolveFilename (module.js:547:15)
2018-10-23T08:42:33.439973+00:00 app[web.1]: at Function.Module._load (module.js:474:25)
2018-10-23T08:42:33.439975+00:00 app[web.1]: at Function.Module.runMain (module.js:693:10)
2018-10-23T08:42:33.439976+00:00 app[web.1]: at startup (bootstrap_node.js:191:16)
2018-10-23T08:42:33.439978+00:00 app[web.1]: at bootstrap_node.js:612:3
Here is my Procfile:
web: node ./index.js
Here is my package.json:
{
"name": "anirec",
"version": "1.0.0",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "hidden"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "hidden"
},
"homepage": "hidden",
"description": "",
"dependencies": {
"body-parser": "^1.18.3",
"ejs": "^2.6.1",
"express": "^4.16.4"
},
"engines": {
"node": "8.11.4"
}
}
Here is an image of my directory:
The app works using local host.
I've tried having my server listen to 'process.env.PORT'. I've tried taking out "main" in my package.json. I've tried a relative path in my Procfile. I've tried reinstalling node_modules. My Procfile is in the same directory as index.js.
What else am I missing? Thanks in advance.
Edit: I've also tried restarting the server/dyno. 'Index.js' is also listed when I type 'git ls-files' into my terminal.

You have case-sensitive issue, your Index.js starts with capital letter, it should be index.js instead.

Related

CircleCi: Nodejs must be start before run npm test

I am new to Circle ci. I'm integrating it into my project and am running into a rather puzzling problem. Specifically locally I have to npm start nodejs server and run npm run test. Everything is as expected with a passing case. But when deploying to circle ci, I get an error. And my guess is that nodejs didn't actually launch to run this simple test case. I have referenced from this project https://github.com/punkdata/nodejs-circleci and it works locally like my project. But strangely it works fine with circle ci. Can someone help me where is the wrong point. Thank you.
My package.json
{
"author": "ThanhDeveloper",
"name": "nextzone",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "nodemon --watch routes --watch controllers --watch services ./bin/www --ignore client",
"test": "mocha"
},
"dependencies": {
"bcrypt": "^5.0.1",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"dotenv": "^16.0.0",
"express": "~4.16.1",
"express-rate-limit": "^6.2.1",
"helmet": "^5.0.2",
"http-errors": "~1.6.3",
"jsonwebtoken": "^8.5.1",
"mocha": "^9.2.1",
"morgan": "^1.9.1",
"pg": "^8.7.3",
"pg-hstore": "^2.3.4",
"request": "^2.88.2",
"sequelize": "^6.16.1",
"xss-clean": "^0.1.1"
},
"devDependencies": {
"concurrently": "^7.0.0",
"nodemon": "^2.0.15"
}
}
test/router.test.js
const request = require("request")
const assert = require('assert')
const base_url = "http://localhost:5001"
describe("Continues integration server", function() {
describe("GET /", function() {
it("returns status code 200", function(done) {
request.get(base_url, function(error, response, body) {
assert.equal(200, response.statusCode);
done();
});
});
});
});
app.js (server)
//import
...
if (process.env.NODE_ENV !== "production") {
app.use(morgan("dev"));
}
//use
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(xss());
app.use(helmet());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// routers and limit request
app.use("/", indexRouter);
app.use("/api/v1/users", limitRequest.apiLimiter(1, 100), usersRouter);
app.use('/api/v1/auth', authRouter);
// middleware
app.use(notFoundMiddleware);
app.use(errorHandlerMiddleware);
module.exports = app;
routes/index
const express = require('express');
const router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.send('Server is running');
});
module.exports = router;
- Response from circle ci
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/1SH1w.png
Npm run test failed from log
> nextzone#0.0.0 test
> mocha
Continues integration server
GET /
1) returns status code 200
0 passing (140ms)
1 failing
1) Continues integration server
GET /
returns status code 200:
Uncaught TypeError: Cannot read properties of undefined (reading 'statusCode')
at Request._callback (test/router.test.js:10:44)
at self.callback (node_modules/request/request.js:185:22)
at Request.emit (node:events:390:28)
at Request.onRequestError (node_modules/request/request.js:877:8)
at ClientRequest.emit (node:events:390:28)
at Socket.socketErrorListener (node:_http_client:447:9)
at Socket.emit (node:events:390:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
Exited with code exit status 1
CircleCI received exit code 1

How to solve Error : cannot find module "ejs"?

I started a new (and first) express.js project using ejs but facing to this following error while accessing to the page :
Error: Cannot find module 'ejs '
Require stack:
- C:\wamp64\www\myproject\node_modules\express\lib\view.js
- C:\wamp64\www\myproject\node_modules\express\lib\application.js
- C:\wamp64\www\myproject\node_modules\express\lib\express.js
- C:\wamp64\www\myproject\node_modules\express\index.js
- C:\wamp64\www\myproject\server.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
at Function.Module._load (node:internal/modules/cjs/loader:769:27)
at Module.require (node:internal/modules/cjs/loader:997:19)
at require (node:internal/modules/cjs/helpers:92:18)
at new View (C:\wamp64\www\myproject\node_modules\express\lib\view.js:81:14)
at Function.render (C:\wamp64\www\myproject\node_modules\express\lib\application.js:570:12)
at ServerResponse.render (C:\wamp64\www\myproject\node_modules\express\lib\response.js:1012:7)
at C:\wamp64\www\myproject\server.js:10:13
at Layer.handle [as handle_request] (C:\wamp64\www\myproject\node_modules\express\lib\router\layer.js:95:5)
at next (C:\wamp64\www\myproject\node_modules\express\lib\router\route.js:137:13)
Here is how I proceed from the beginning :
Created a new folder called myproject
Created a new file called server.js
node init
Modified package.json to add nodemon
npm install --save nodemon
npm install --save express
npm install --save ejs
My file server.js :
var app = require('express')();
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
res.setHeader('Content-Type', 'text/plain');
res.send('Accueil');
})
.get('/album', function(req, res){
res.setHeader('Content-Type', 'text/plain');
res.render('album.ejs ', {name :'yop'});
})
.use(function(req, res, next){
res.setHeader('Content-Type', 'text/plain');
res.status(404).send('Page introuvable !');
});
app.listen(8080);
My file package.json :
{
"name": "myproject",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.5",
"express": "^4.17.1",
"nodemon": "^2.0.6"
}
}
My project's structure :
My project directory
node_modules folder
views folder
album.ejs file
package.json
server.js
You add one extra space accidentally behind the ejs.
res.render('album.ejs ', {name :'yop'});
Remove that space like below.
res.render('album.ejs', {name :'yop'});
And you could just use the file name without extension name.
res.render('album', {name :'yop'});
in your server.js
app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')
add this to your code just below app.set('view engine', 'ejs)
app.engine('ejs', require('ejs').__express);
If you already had installed ejs, you must uninstall and install it again
Here are the steps:
npm uninstall ejs --save
npm install ejs --save

Failed at the app#1.0.0 start script This is probably not a problem with npm. There is likely additional logging output above

Hi Guys, I have created a little project of Mern stack. I am deploying it correctly on Heroku. But as soon as I am checking her on Heroku after deploying, then Failed to load resource: the server responded with a status of 503 (Service Unavailable) error is coming.
But as soon as I run heroku local in cmd after deploying then it is working correctly. I am giving below the heroku setup code. Please guide me. please ........
package.sjon file of backend
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "npm install && node index",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"dependencies": {
"config": "^3.3.1",
"express": "~4.16.1",
"express-fileupload": "^1.1.7-alpha.3",
"mongoose": "^5.9.12",
"nodemailer": "^6.4.6"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Index.js file of backend
var express = require('express');
var path = require('path');
const connectDB = require('./config/db')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var studentRouter = require('./routes/student')
var app = express();
connectDB();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('client/build'))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
app.use('/', indexRouter);
app.use('/', studentRouter);
app.use('/users', usersRouter);
if (process.env.NODE_ENV == "production") {
app.use(express.static('client/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
}
var port = process.env.PORT || '8000';
app.listen(port, () => {
console.log(`server run port ${port}`);
})
module.exports = app;
All these codes are absolutely correct. I had a problem creating a cluster in mongodb atlas. The problem was that I had selected add current ip address while creating the cluster. Whereas I had to select allow from anywhere. So now I have selected the book. And now it is doing the right thing.
In my case, changing network access form anywhere in my MongoDB cluster, fixed the problem.
Also, don't forget to hit restart all dynos.

MongoDB Atlas error: invalid schema, expected mongodb

I am running through the Hello World app tutorial in GCP. And I am getting stuck at the server.js step.
The code of the server.js is as below:
'use strict';
const mongodb = require('mongodb');
const http = require('http');
const nconf = require('nconf');
let uri = 'mongodb+srv://my_name:<mypassword>#mydatabase-clr75.gcp.mongodb.net/test?retryWrites=true&w=majority';
if (nconf.get('mongoDatabase')) {
uri = `${uri}/${nconf.get('mongoDatabase')}`;
}
console.log(uri);
mongodb.MongoClient.connect(uri, (err, db) => {
if (err) {
throw err;
}
// Create a simple little server.
http.createServer((req, res) => {
if (req.url === '/_ah/health') {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write('OK');
res.end();
return;
}
const collection = db.collection('Messages');
var datetime = new Date();
const msg = {
msgDescription: '\nHello World received on ' + datetime
};
collection.insert(msg, (err) => {
if (err) {
throw err;
}
// push out a range
let msglist = '';
collection.find().toArray((err, data) => {
if (err) {
throw err;
}
data.forEach((msg) => {
msglist += `${msg.msgDescription}; `;
});
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write('Messages received so far:\n');
res.end(msglist);
});
});
}).listen(process.env.PORT || 8080, () => {
console.log('started web process');
});
});
I receive the error as below:
mongodb+srv://my_name:#mydatabase-clr75.gcp.mongodb.net/test?retryWrites=true&w=majority
/home/herboratory/node_modules/mongodb/lib/url_parser.js:19
throw new Error('invalid schema, expected mongodb');
^ Error: invalid schema, expected mongodb
at module.exports (/home/herboratory/node_modules/mongodb/lib/url_parser.js:19:11)
at connect (/home/herboratory/node_modules/mongodb/lib/mongo_client.js:486:16)
at Function.MongoClient.connect (/home/herboratory/node_modules/mongodb/lib/mongo_client.js:250:3)
at Object. (/home/herboratory/server.js:12:21)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! test#1.0.0 start: node
server.js npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the
test#1.0.0 start script. npm ERR! This is probably not a problem with
npm. There is likely additional logging output above. npm ERR! A
complete log of this run can be found in: npm ERR!
/home/herboratory/.npm/_logs/2019-06-26T03_58_26_823Z-debug.log
I was wondering it should be the format error after reading some other posts here with the same error line, so I've tried '...', "..." and without any quotation mark but still remain error. Would please guide me where's the error?
Except for the URI, is there anywhere else I also need to modify inside the code? As far as I know from the instruction I just need to insert my own Atlas Connection string.
Many thanks.
The error invalid schema, expected mongodb means that you're using an outdated node driver version. The old driver cannot parse the new mongodb+srv URI scheme.
Support for the mongodb+srv scheme was added in the node driver version 3.0 in this ticket: NODE-1145.
Upgrade your node driver using:
$ npm install mongodb
and the error should go away.
I had the same error. The problem was with setup in mongoDB Atlas and setup in my Application.
In mongoDB Atlas:
Create DATABASE and COLLECTION
Create Database User
Add your IP Address (public) in IP Whitelist, Network Access
Example of my solution:
File .env
MONGO_URI=mongodb+srv://jmendoza:your-password#cluster0-7rxkw.mongodb.net/nodeapi?retryWrites=true&w=majority
PORT=3000
File app.js
const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const { postRoutes } = require('./routes/posts');
const app = express();
const port = process.env.PORT || 3000;
dotenv.config();
// BD
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('mongoDB, Atlas. Connected'))
.catch((err) => console.error(err));
// Middleware
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(expressValidator());
// Routes
app.use('/api/v1', postRoutes);
app.listen(port, () => {
console.log(`A NodeJS API is listining on port: ${port}`);
});
File package.json
{
"name": "node-api",
"version": "1.0.0",
"description": "A NodeJS API",
"main": "app.js",
"scripts": {
"dev": "nodemon app.js"
},
"keywords": [
"node",
"api"
],
"author": "Jonathan Mendoza",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-validator": "^5.3.1",
"mongoose": "^5.9.7",
"morgan": "^1.9.1",
"nodemon": "^2.0.3"
}
}
Running application (console)
jmendoza#jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ npm run dev
> node-api#1.0.0 dev /home/jmendoza/IdeaProjects/NodeJS-API-Course/Basic-Node-API
> nodemon app.js
[nodemon] 2.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
mongoDB, Atlas. Connected
NodeJS Version
jmendoza#jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ node -v
v13.12.0
You can see my full code on GitHub:
https://github.com/JonathanM2ndoza/NodeJS-API-Course/tree/master/Basic-Node-API

Nodejs Heroku Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

I have tried number of "Error R10" Solutions, but it doesn't solve the problem for a simple Hello World like Nodejs app with server.js, package.json, index.html and node_module
Hereby adding server.js, package.json and error log
Currently trying this app on free heroku acount
Is it necessary to upload nodejs app on github to host it on heroku
server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var port = 3000;
var app = express();
// Set Static Folder
app.use(express.static(__dirname));
// Body Parser MW
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
app.use(express.static(__dirname + '/'));
} else {
app.use(express.static(__dirname + '/'));
}
app.get("/", function(req, res){
res.render("index.html");
});
app.listen(port, function(){
console.log("Server started ..!");
});
package.json
{
"name": "es1",
"version": "1.0.0",
"description": "eS",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.16.0",
"express": "^4.14.0"
}
}
Attaching heroku logs:
https://drive.google.com/open?id=0B4XtAe7mRM6UVllTQWh1dmplZk0
Change the value of port as follows:
var port = process.env.PORT || 3000;

Resources